@collective-intelligence/ai 0.9.1 → 0.9.3
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/AGENTS.md +3 -1
- package/dist/api/attachments-api.d.ts +4 -2
- package/dist/api/catalog-api.d.ts +8 -4
- package/dist/api/chat-api.d.ts +48 -23
- package/dist/api/chat-surface-api.d.ts +88 -43
- package/dist/api/conversations.d.ts +8 -0
- package/dist/api/errors.d.ts +8 -4
- package/dist/api/feedback-api.d.ts +4 -2
- package/dist/api/index.d.ts +2 -1
- package/dist/api/projects-api.d.ts +16 -8
- package/dist/api/speech-api.d.ts +8 -4
- package/dist/api/turns.d.ts +16 -2
- package/dist/api.d.ts +2 -1
- package/dist/api.js +1 -1
- package/dist/domain/data-parts.d.ts +28 -1
- package/dist/domain/errors.d.ts +8 -0
- package/dist/domain/index.d.ts +1 -1
- package/dist/domain-4fej3j1a.js +1 -0
- package/dist/{domain-54qeg701.js → domain-673qdd7n.js} +1 -1
- package/dist/{domain-50vzrrp9.js → domain-s8r5t4nq.js} +1 -1
- package/dist/domain-te8xf29h.js +2 -0
- package/dist/domain.d.ts +1 -1
- package/dist/domain.js +1 -1
- package/dist/headless/chat-registry.d.ts +3 -2
- package/dist/headless/chat-surface.d.ts +88 -43
- package/dist/headless.js +1 -1
- package/dist/transport/chat-client.d.ts +10 -2
- package/dist/transport/chat-transport.d.ts +2 -2
- package/dist/transport.js +1 -1
- package/dist/views/run-trace/run-stream.d.ts +2 -1
- package/dist/views.js +1 -1
- package/docs/guide/develop/external-apps.md +2 -0
- package/package.json +6 -6
- package/dist/domain-8rwbw2ah.js +0 -2
- package/dist/domain-tg4azwc2.js +0 -1
- /package/dist/{domain-5fpd4fte.js → domain-6wbbkjz0.js} +0 -0
|
@@ -116,6 +116,8 @@ Access tokens always live 300 seconds. A confidential client that passes its `cl
|
|
|
116
116
|
> public client gets no renewal credential, so the session ends when the first
|
|
117
117
|
> access token expires, whatever `sessionTtlSeconds` says.
|
|
118
118
|
|
|
119
|
+
After each start, the first signed-in request also reads CI's token key set. Call `auth.warm?.()` at boot, for example in Next.js `instrumentation.ts` `register`, without waiting for it before the server starts. It reads the key set into the SDK's cache, never rejects, and resolves `{ ok: false, error }` when CI does not answer; the first request then reads the key set itself, as without a warm-up.
|
|
120
|
+
|
|
119
121
|
A revoked grant reaches the app at the next renewal, so within 300 seconds. It reaches the app at once when a forwarded CI answer is a `401` or carries a changed `x-access-version`, which `auth.observeCiResponse` watches for. A user who signs in without a grant that holds the app gate does not bounce straight back with `access_denied`. CI first shows its own access-denied page with "Switch account" and "Back to the application".
|
|
120
122
|
|
|
121
123
|
> **Note:** Consent follows the app's `applicationConsent` (`inherit`, `ask` or `skip`),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/ai",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.3",
|
|
4
4
|
"description": "The Collective Intelligence AI package: the CI message domain, the chat contract, the chat transports, the headless chat session and the chat views, one subpath per layer.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -58,8 +58,8 @@
|
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
60
|
"@ai-sdk/react": "^4.0.177",
|
|
61
|
-
"@collective-intelligence/effect-xstate": "0.9.
|
|
62
|
-
"@collective-intelligence/ui-react": "0.9.
|
|
61
|
+
"@collective-intelligence/effect-xstate": "0.9.3",
|
|
62
|
+
"@collective-intelligence/ui-react": "0.9.3",
|
|
63
63
|
"@tanstack/react-query": "^5.101.4",
|
|
64
64
|
"@xstate/react": "^6.1.0",
|
|
65
65
|
"ai": ">=7.0.173 <8",
|
|
@@ -95,8 +95,8 @@
|
|
|
95
95
|
},
|
|
96
96
|
"devDependencies": {
|
|
97
97
|
"@ai-sdk/react": "4.0.177",
|
|
98
|
-
"@collective-intelligence/effect-xstate": "0.9.
|
|
99
|
-
"@collective-intelligence/ui-react": "0.9.
|
|
98
|
+
"@collective-intelligence/effect-xstate": "0.9.3",
|
|
99
|
+
"@collective-intelligence/ui-react": "0.9.3",
|
|
100
100
|
"@effect/eslint-plugin": "0.3.2",
|
|
101
101
|
"@oxlint/plugins": "1.94.0",
|
|
102
102
|
"@punks/lints": "0.2.0",
|
|
@@ -121,5 +121,5 @@
|
|
|
121
121
|
"vitest": "5.0.2",
|
|
122
122
|
"xstate": "5.33.3"
|
|
123
123
|
},
|
|
124
|
-
"gitHead": "
|
|
124
|
+
"gitHead": "5a6e5e667ce6bd14ad1d149062388531fef7b436"
|
|
125
125
|
}
|
package/dist/domain-8rwbw2ah.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{Uuid,ConversationId2,InvocationId2,AgentId2,ProjectId2,ProjectFileId2,AttachmentId2,QueuedMessageId2,SteeringMessageId2,SpeechClipId2}from"./domain-5fpd4fte.js";import{draftSubjectKinds2,ciDataPartSchemas2,contextTrailEntrySchema2,placeKinds2}from"./domain-50vzrrp9.js";import{Multipart}from"effect/http";import{HttpApiEndpoint,HttpApiGroup,HttpApiSchema as HttpApiSchema2}from"effect/http-api";import*as Schema3 from"effect/Schema";import{HttpApiSchema}from"effect/http-api";import*as Schema from"effect/Schema";var chatRefusalReasons2=["capability_missing","app_disabled","principal_not_allowed","not_available_here","approval_not_allowed"];var chatConflictReasons2=["turn_ended","intent_turn_busy","intent_turn_agent"];var uploadRejectionReasons2=["unsupported","oversized","malformed","too_many_files"];var statusOf={conflict:409,forbidden:403,internal:500,invalid_request:400,not_found:404,rate_limited:429,unauthenticated:401,unavailable:503};var failure=(code,fields)=>Schema.Struct({correlationId:Schema.String,error:Schema.Struct({...fields,code:Schema.Literal(code),message:Schema.String,retryable:Schema.Boolean}),ok:Schema.Literal(false)}).pipe(HttpApiSchema.status(statusOf[code]));var chatFailures=[failure("invalid_request",{details:Schema.optionalKey(Schema.Struct({filename:Schema.optionalKey(Schema.String),reason:Schema.Literals(uploadRejectionReasons2)}))}),failure("unauthenticated",{}),failure("forbidden",{details:Schema.Struct({reason:Schema.Literals(chatRefusalReasons2)})}),failure("not_found",{}),failure("conflict",{details:Schema.optionalKey(Schema.Struct({reason:Schema.Literals(chatConflictReasons2)}))}),failure("rate_limited",{}),failure("internal",{}),failure("unavailable",{})];import*as Schema2 from"effect/Schema";var partHeaderBytes=32*1024;var maxFileBytes=10*1024*1024;var maxUploadPartBytes=maxFileBytes+partHeaderBytes;var maxAttachmentsPerUpload=10;var DownloadUrl=Schema2.Struct({expiresIn:Schema2.Int,url:Schema2.String});var storedAttachmentFields={characterCount:Schema2.Int,contentType:Schema2.NullOr(Schema2.String),extension:Schema2.NullOr(Schema2.String),extractionStatus:Schema2.String,filename:Schema2.String,id:AttachmentId2,sizeBytes:Schema2.Int,truncated:Schema2.Boolean,unavailableReason:Schema2.NullOr(Schema2.String)};var UploadAttachmentsPath=Schema3.Struct({conversationId:ConversationId2});var AttachmentsUpload=Schema3.Struct({files:Multipart.FilesSchema}).pipe(HttpApiSchema2.asMultipart({maxFileSize:maxUploadPartBytes,maxParts:maxAttachmentsPerUpload}));var UploadedAttachment=Schema3.Struct(storedAttachmentFields);var UploadAttachmentsResponse=Schema3.Struct({attachments:Schema3.Array(UploadedAttachment)});var AttachmentPath=Schema3.Struct({attachmentId:AttachmentId2,conversationId:ConversationId2});var error=chatFailures;class ChatAttachmentsApi2 extends HttpApiGroup.make("chatAttachments").add(HttpApiEndpoint.post("uploadAttachments","/chat/conversations/:conversationId/attachments",{error,params:UploadAttachmentsPath,payload:AttachmentsUpload,success:UploadAttachmentsResponse.pipe(HttpApiSchema2.status(201))})).add(HttpApiEndpoint.get("getAttachmentDownloadUrl","/chat/conversations/:conversationId/attachments/:attachmentId/download-url",{error,params:AttachmentPath,success:DownloadUrl})){}import{HttpApiEndpoint as HttpApiEndpoint2,HttpApiGroup as HttpApiGroup2}from"effect/http-api";import*as Schema4 from"effect/Schema";var AgentDirectoryEntry=Schema4.Struct({agentType:Schema4.Literals(["organization","personal"]),degraded:Schema4.Boolean,displayName:Schema4.String,fqn:Schema4.String,id:AgentId2,paused:Schema4.Boolean,responsibility:Schema4.String});var ListAgentsResponse=Schema4.Struct({data:Schema4.Array(AgentDirectoryEntry)});var SkillSourceMode=Schema4.Literals(["user","skill"]);var SkillDirectoryEntry=Schema4.Struct({dataAccess:Schema4.NullOr(Schema4.Struct({datasets:Schema4.optionalKey(SkillSourceMode),documents:Schema4.optionalKey(SkillSourceMode),knowledge:Schema4.optionalKey(SkillSourceMode)})),description:Schema4.NullOr(Schema4.String),fqn:Schema4.String,id:Schema4.String,name:Schema4.String,slug:Schema4.String});var ListSkillsResponse=Schema4.Struct({data:Schema4.Array(SkillDirectoryEntry)});var ListToolsQuery=Schema4.Struct({conversationId:Schema4.optionalKey(ConversationId2),usageScope:Schema4.optionalKey(Schema4.Literals(["chat","skill","automation"]))});var ToolCatalogEntry=Schema4.Struct({collectionId:Schema4.NullOr(Schema4.String),description:Schema4.String,displayName:Schema4.String,fqn:Schema4.String,id:Schema4.String,inputSchema:Schema4.Record(Schema4.String,Schema4.Json)});var ListToolsResponse=Schema4.Struct({data:Schema4.Array(ToolCatalogEntry)});var AttachmentFileType=Schema4.Struct({extension:Schema4.String,mediaTypes:Schema4.Array(Schema4.String)});var AttachmentCapabilities=Schema4.Struct({fileTypes:Schema4.Array(AttachmentFileType),projectFileTypes:Schema4.Array(AttachmentFileType)});var error2=chatFailures;class ChatCatalogApi2 extends HttpApiGroup2.make("chatCatalog").add(HttpApiEndpoint2.get("listAgents","/chat/agents",{error:error2,success:ListAgentsResponse})).add(HttpApiEndpoint2.get("listSkills","/chat/skills",{error:error2,success:ListSkillsResponse})).add(HttpApiEndpoint2.get("listTools","/chat/tools",{error:error2,query:ListToolsQuery,success:ListToolsResponse})).add(HttpApiEndpoint2.get("getAttachmentCapabilities","/chat/attachment-capabilities",{error:error2,success:AttachmentCapabilities})){}import{HttpApiEndpoint as HttpApiEndpoint4,HttpApiGroup as HttpApiGroup4,HttpApiSchema as HttpApiSchema4}from"effect/http-api";import*as Schema5 from"effect/Schema";var EvidenceNavigationPath=Schema5.Struct({invocationId:InvocationId2});var EvidenceNavigation=Schema5.Union([Schema5.Struct({entityId:Uuid,kind:Schema5.Literal("entity")}),Schema5.Struct({fileId:Uuid,kind:Schema5.Literal("file")}),Schema5.Struct({kind:Schema5.Literal("external_url"),url:Schema5.String})]);var EvidenceNavigationRequest=Schema5.Struct({evidenceId:Schema5.NonEmptyString,navigation:EvidenceNavigation});var EvidenceNavigationTarget=Schema5.Union([Schema5.Struct({entityId:Uuid,kind:Schema5.Literal("entity")}),Schema5.Struct({fileId:Uuid,kind:Schema5.Literal("file"),mediaUrl:Schema5.optionalKey(Schema5.String)}),Schema5.Struct({kind:Schema5.Literal("external_url"),url:Schema5.String})]);var EvidenceNavigationResponse=Schema5.Struct({target:Schema5.NullOr(EvidenceNavigationTarget)});var ArtifactProgress=Schema5.Struct({currentArtifact:Schema5.NullOr(Schema5.Struct({artifactId:Uuid,contentType:Schema5.NullOr(Schema5.String),filename:Schema5.String,role:Schema5.String,sourceKind:Schema5.String})),failed:Schema5.Int,leased:Schema5.Int,pending:Schema5.Int,processed:Schema5.Int,skipped:Schema5.Int});import*as Schema7 from"effect/Schema";import*as Schema6 from"effect/Schema";import*as SchemaTransformation from"effect/SchemaTransformation";var PlaceKind=Schema6.Literals(placeKinds2);var PlaceSchema=Schema6.Union([Schema6.Struct({id:Schema6.String,kind:Schema6.Literal("studio_app")}),Schema6.Struct({id:Schema6.String,kind:Schema6.Literal("external_app")}),Schema6.Struct({id:Schema6.String,kind:Schema6.Literal("dashboard")})]);var ConversationSubjectSchema=Schema6.Struct({id:Schema6.String,kind:Schema6.Literals(draftSubjectKinds2)});var ConversationPath=Schema6.Struct({conversationId:ConversationId2});var ConversationSchema=Schema6.Struct({agentId:Schema6.NullOr(AgentId2),createdAt:Schema6.NullOr(Schema6.Date),id:ConversationId2,lastActivityAt:Schema6.NullOr(Schema6.Date),lastActivityInvocationId:Schema6.NullOr(Schema6.String),memoryEnabled:Schema6.Boolean,organizationId:Schema6.String,origin:PlaceSchema,projectId:Schema6.NullOr(ProjectId2),subject:Schema6.NullOr(ConversationSubjectSchema),title:Schema6.String,updatedAt:Schema6.NullOr(Schema6.Date),userId:Schema6.NullOr(Schema6.String)});var PlaceParam=Schema6.TemplateLiteralParser([PlaceKind,":",Schema6.String]).pipe(Schema6.decodeTo(PlaceSchema,SchemaTransformation.transform({decode:([kind,,id])=>({id,kind}),encode:(place)=>[place.kind,":",place.id]})));var SubjectParam=Schema6.TemplateLiteralParser([Schema6.Literals(draftSubjectKinds2),":",Schema6.String]).pipe(Schema6.decodeTo(ConversationSubjectSchema,SchemaTransformation.transform({decode:([kind,,id])=>({id,kind}),encode:(subject)=>[subject.kind,":",subject.id]})));var ListConversationsQuery=Schema6.Struct({historyScope:Schema6.optionalKey(Schema6.Array(PlaceParam)),subject:Schema6.optionalKey(SubjectParam)});var ListConversationsResponse=Schema6.Struct({data:Schema6.Array(ConversationSchema)});var CreateConversationRequest=Schema6.Struct({agentId:Schema6.optionalKey(AgentId2),projectId:Schema6.optionalKey(ProjectId2),title:Schema6.optionalKey(Schema6.String)});var UpdateConversationRequest=Schema6.Struct({memoryEnabled:Schema6.optionalKey(Schema6.Boolean),projectId:Schema6.optionalKey(Schema6.NullOr(ProjectId2)),title:Schema6.optionalKey(Schema6.String)});var CompactionState=Schema7.Struct({active:Schema7.Boolean,activeSummary:Schema7.NullOr(Schema7.Struct({id:Uuid,status:Schema7.String,summary:Schema7.String,trigger:Schema7.String})),boundary:Schema7.NullOr(Schema7.Struct({compactedThroughInvocationId:Schema7.NullOr(InvocationId2),coveredInvocationCount:Schema7.Int,coveredMessageCount:Schema7.Int}))});var CompactionResponse=Schema7.Struct({compaction:CompactionState,conversation:ConversationSchema});import*as Effect from"effect/Effect";import*as Schema8 from"effect/Schema";var NamedPlace=Schema8.Struct({id:Schema8.String,kind:PlaceKind,name:Schema8.NullOr(Schema8.String)});var PlaceContextSchema=Schema8.Struct({contextTrailEnabled:Schema8.Boolean.pipe(Schema8.withDecodingDefaultKey(Effect.succeed(false))),contextTrailVisible:Schema8.Boolean.pipe(Schema8.withDecodingDefaultKey(Effect.succeed(false))),places:Schema8.Array(NamedPlace),readAloud:Schema8.Boolean,voiceInputMode:Schema8.optionalKey(Schema8.Literals(["local","remote"]))});import*as Schema10 from"effect/Schema";import{HttpApiEndpoint as HttpApiEndpoint3,HttpApiGroup as HttpApiGroup3}from"effect/http-api";import*as Schema9 from"effect/Schema";var AnswerSentiment=Schema9.Literals(["positive","negative"]);var CurrentUserFeedback=Schema9.Struct({sentiment:Schema9.NullOr(AnswerSentiment),submitterNote:Schema9.NullOr(Schema9.String)});var AnswerFeedbackPath=Schema9.Struct({invocationId:InvocationId2});var AnswerFeedbackRequest=Schema9.Struct({sentiment:AnswerSentiment,submitterNote:Schema9.optionalKey(Schema9.String)});var AnswerFeedbackResponse=Schema9.Struct({currentUserFeedback:CurrentUserFeedback,feedbackTargetId:Uuid});var error3=chatFailures;class ChatFeedbackApi2 extends HttpApiGroup3.make("chatFeedback").add(HttpApiEndpoint3.put("putAnswerFeedback","/chat/answers/:invocationId/feedback",{error:error3,params:AnswerFeedbackPath,payload:AnswerFeedbackRequest,success:AnswerFeedbackResponse})).add(HttpApiEndpoint3.delete("clearAnswerFeedback","/chat/answers/:invocationId/feedback",{error:error3,params:AnswerFeedbackPath,success:AnswerFeedbackResponse})){}var TranscriptToolDisplay=Schema10.Union([Schema10.Struct({kind:Schema10.Literal("text"),text:Schema10.String}),Schema10.Struct({kind:Schema10.Literal("unavailable")})]);var TranscriptAttachment=Schema10.Struct({...storedAttachmentFields,mediaUrl:Schema10.NullOr(Schema10.String)});var ToolDisplayPart=Schema10.Struct({data:Schema10.Unknown,description:Schema10.NullOr(Schema10.String),metadata:Schema10.Record(Schema10.String,Schema10.Unknown),title:Schema10.NullOr(Schema10.String),type:Schema10.String});var ToolTrace=Schema10.Struct({displayName:Schema10.NullOr(Schema10.String),displayParts:Schema10.Array(ToolDisplayPart),durationMs:Schema10.NullOr(Schema10.Finite),error:Schema10.NullOr(Schema10.String),fqn:Schema10.NullOr(Schema10.String),toolCallId:Schema10.optionalKey(Schema10.NullOr(Schema10.String)),toolId:Schema10.NullOr(Schema10.String)});var InteractionOption=Schema10.Struct({description:Schema10.NullOr(Schema10.String),id:Schema10.String,label:Schema10.String});var InteractionOperation=Schema10.Union([Schema10.Struct({displayName:Schema10.String,kind:Schema10.Literal("tool"),toolFqn:Schema10.String,toolId:Uuid}),Schema10.Struct({displayName:Schema10.String,fqn:Schema10.String,inputs:Schema10.Record(Schema10.String,Schema10.Json),kind:Schema10.Literal("intent")})]);var UserInteraction=Schema10.Struct({allowFreeText:Schema10.Boolean,id:Uuid,kind:Schema10.Literals(["approval","question"]),mode:Schema10.NullOr(Schema10.Literals(["open","single_choice"])),operation:Schema10.NullOr(InteractionOperation),options:Schema10.Array(InteractionOption),preview:Schema10.NullOr(Schema10.String),prompt:Schema10.String,safePreview:Schema10.NullOr(Schema10.String),status:Schema10.Literals(["pending","responding","completed","cancelled","failed"]),summary:Schema10.NullOr(Schema10.String)});var ProcessingEvent=Schema10.Struct({data:Schema10.Record(Schema10.String,Schema10.Unknown),event:Schema10.String});var MemoryEvidenceEvent=Schema10.Struct({category:Schema10.NullOr(Schema10.String),conversationId:Schema10.NullOr(ConversationId2),invocationId:Schema10.NullOr(InvocationId2),kind:Schema10.String,lifecycleStatus:Schema10.NullOr(Schema10.String),memoryId:Schema10.NullOr(Uuid),reason:Schema10.NullOr(Schema10.String),scope:Schema10.NullOr(Schema10.String)});var TranscriptIntentCards=Schema10.optionalKey(Schema10.Array(ciDataPartSchemas2["intent-card"]));var TranscriptRun=Schema10.Struct({approvalRequestId:Schema10.NullOr(Uuid),conversationId:ConversationId2,durationMs:Schema10.Finite,inputTokens:Schema10.Int,intentCards:TranscriptIntentCards,invocationId:InvocationId2,memoryEvidence:Schema10.NullOr(Schema10.Struct({events:Schema10.Array(MemoryEvidenceEvent)})),model:Schema10.NullOr(Schema10.String),output:Schema10.String,outputTokens:Schema10.Int,permissionWait:Schema10.NullOr(Schema10.Struct({capabilityKind:Schema10.Literals(["skill","tool"]),invocationId:InvocationId2,subjectId:Uuid})),processingEvents:Schema10.Array(ProcessingEvent),skillOutcome:Schema10.NullOr(Schema10.String),status:Schema10.String,toolTrace:Schema10.Array(ToolTrace),traceLink:Schema10.optionalKey(Schema10.String),userInteraction:Schema10.NullOr(UserInteraction)});var TranscriptMessage=Schema10.Struct({approvalRequestId:Schema10.NullOr(Uuid),attachments:Schema10.Array(TranscriptAttachment),content:Schema10.String,contextTrail:Schema10.optionalKey(Schema10.Array(contextTrailEntrySchema2)),conversationId:ConversationId2,currentUserFeedback:Schema10.optionalKey(CurrentUserFeedback),feedbackTargetId:Schema10.optionalKey(Uuid),invocationId:InvocationId2,processingEvents:Schema10.Array(ProcessingEvent),role:Schema10.Literals(["assistant","user"]),run:Schema10.optionalKey(TranscriptRun),status:Schema10.String,toolDisplay:TranscriptToolDisplay});var TranscriptSteeringMessage=Schema10.Struct({attachments:Schema10.Array(TranscriptAttachment),claimedAt:Schema10.NullOr(Schema10.Date),content:Schema10.String,id:SteeringMessageId2,invocationId:InvocationId2});var TranscriptAgentTurn=Schema10.Struct({completedAt:Schema10.NullOr(Schema10.Date),createdAt:Schema10.Date,input:Schema10.String,intentCards:TranscriptIntentCards,message:Schema10.NullOr(Schema10.String),sequence:Schema10.Int,status:Schema10.Literals(["pending","completed","failed","cancelled"]),turnId:Uuid});var TranscriptSchema2=Schema10.Struct({agentTurns:Schema10.Array(TranscriptAgentTurn),conversation:Schema10.Struct({agent:Schema10.NullOr(Schema10.Struct({displayName:Schema10.String,id:AgentId2})),compaction:CompactionState,contextUsage:Schema10.Struct({estimatedCharacters:Schema10.Int,fillRatio:Schema10.Finite,thresholdCharacters:Schema10.Int}),id:ConversationId2,title:Schema10.String}),messages:Schema10.Array(TranscriptMessage),steeringMessages:Schema10.Array(TranscriptSteeringMessage)});import{HttpApiSchema as HttpApiSchema3}from"effect/http-api";import*as Schema11 from"effect/Schema";var UIMessageEventStream=Schema11.String.pipe(HttpApiSchema3.asText({contentType:"text/event-stream"}));var UIMessagePart=Schema11.StructWithRest(Schema11.Struct({type:Schema11.String}),[Schema11.Record(Schema11.String,Schema11.Unknown)]);var ChatSendMessage=Schema11.Struct({id:Schema11.NonEmptyString,metadata:Schema11.optionalKey(Schema11.Unknown),parts:Schema11.Array(UIMessagePart),role:Schema11.Literals(["system","user","assistant"])});var ChatSendRequestSchema=Schema11.Struct({message:ChatSendMessage,messageId:Schema11.optionalKey(Schema11.String),trigger:Schema11.Literals(["submit-message","regenerate-message"])});var RunPath=Schema11.Struct({runId:InvocationId2});var TurnStatus=Schema11.Literals(["cancelled","completed","error","running","waiting_for_approval"]);var TurnPath=Schema11.Struct({invocationId:InvocationId2});var ConversationTurnPath=Schema11.Struct({conversationId:ConversationId2,invocationId:InvocationId2});var TurnWaitResponse=Schema11.Struct({waiting:Schema11.Boolean});var CancelTurnResponse=Schema11.Struct({invocationId:InvocationId2,status:TurnStatus});var QueuedMessageRevision=Schema11.Int.check(Schema11.isGreaterThanOrEqualTo(1));var ClientMessageId=Uuid;var QueuedMessageSchema=Schema11.Struct({content:Schema11.String,createdAt:Schema11.Date,id:QueuedMessageId2,invocationId:Schema11.NullOr(InvocationId2),position:Schema11.Int,revision:QueuedMessageRevision,status:Schema11.Literals(["waiting","claimed","removed"])});var SendSteeringMessageRequest=Schema11.Struct({clientMessageId:ClientMessageId,content:Schema11.String,invocationId:InvocationId2});var SendSteeringMessageResponseSchema=Schema11.Union([Schema11.Struct({conversationId:ConversationId2,invocationId:InvocationId2,outcome:Schema11.Literal("started"),status:TurnStatus}),Schema11.Struct({conversationId:ConversationId2,invocationId:InvocationId2,outcome:Schema11.Literal("saved"),status:TurnStatus,steeringMessageId:SteeringMessageId2}),Schema11.Struct({conversationId:ConversationId2,outcome:Schema11.Literal("queued"),queuedMessageId:QueuedMessageId2,revision:QueuedMessageRevision})]);var QueueMessageRequest=Schema11.Struct({clientMessageId:ClientMessageId,content:Schema11.String});var QueueMessageResponseSchema=Schema11.Union([Schema11.Struct({conversationId:ConversationId2,outcome:Schema11.Literal("queued"),queuedMessage:QueuedMessageSchema}),Schema11.Struct({conversationId:ConversationId2,invocationId:Schema11.optionalKey(InvocationId2),outcome:Schema11.Literal("started"),queuedMessageId:Schema11.optionalKey(QueuedMessageId2)}),Schema11.Struct({conversationId:ConversationId2,invocationId:InvocationId2,outcome:Schema11.Literal("saved"),steeringMessageId:SteeringMessageId2})]);var ListQueuedMessagesResponse=Schema11.Struct({data:Schema11.Array(QueuedMessageSchema)});var QueuedMessagePath=Schema11.Struct({conversationId:ConversationId2,queuedMessageId:QueuedMessageId2});var UpdateQueuedMessageRequest=Schema11.Struct({content:Schema11.String,revision:QueuedMessageRevision});var RemoveQueuedMessageQuery=Schema11.Struct({revision:Schema11.NumberFromString.pipe(Schema11.check(Schema11.isInt(),Schema11.isGreaterThanOrEqualTo(1)))});var error4=chatFailures;class ChatApi2 extends HttpApiGroup4.make("chat").add(HttpApiEndpoint4.get("listConversations","/chat/conversations",{error:error4,query:ListConversationsQuery,success:ListConversationsResponse})).add(HttpApiEndpoint4.post("createConversation","/chat/conversations",{error:error4,payload:CreateConversationRequest,success:ConversationSchema.pipe(HttpApiSchema4.status(201))})).add(HttpApiEndpoint4.get("getConversation","/chat/conversations/:conversationId",{error:error4,params:ConversationPath,success:ConversationSchema})).add(HttpApiEndpoint4.patch("updateConversation","/chat/conversations/:conversationId",{error:error4,params:ConversationPath,payload:UpdateConversationRequest,success:ConversationSchema})).add(HttpApiEndpoint4.delete("deleteConversation","/chat/conversations/:conversationId",{error:error4,params:ConversationPath,success:HttpApiSchema4.NoContent})).add(HttpApiEndpoint4.get("getTranscript","/chat/conversations/:conversationId/transcript",{error:error4,params:ConversationPath,success:TranscriptSchema2})).add(HttpApiEndpoint4.post("send","/chat/:conversationId",{error:error4,params:ConversationPath,payload:ChatSendRequestSchema,success:UIMessageEventStream})).add(HttpApiEndpoint4.get("resumeStream","/chat/:conversationId/stream",{error:error4,params:ConversationPath,success:[UIMessageEventStream,HttpApiSchema4.NoContent]})).add(HttpApiEndpoint4.get("streamRun","/runs/:runId/stream",{error:error4,params:RunPath,success:UIMessageEventStream})).add(HttpApiEndpoint4.get("watchTurnWait","/chat/conversations/:conversationId/turns/:invocationId/wait",{error:error4,params:ConversationTurnPath,success:TurnWaitResponse})).add(HttpApiEndpoint4.post("cancelTurn","/chat/turns/:invocationId/cancel",{error:error4,params:TurnPath,success:CancelTurnResponse})).add(HttpApiEndpoint4.post("sendSteeringMessage","/chat/conversations/:conversationId/steering-messages",{error:error4,params:ConversationPath,payload:SendSteeringMessageRequest,success:SendSteeringMessageResponseSchema})).add(HttpApiEndpoint4.post("queueMessage","/chat/conversations/:conversationId/queued-messages",{error:error4,params:ConversationPath,payload:QueueMessageRequest,success:QueueMessageResponseSchema})).add(HttpApiEndpoint4.get("listQueuedMessages","/chat/conversations/:conversationId/queued-messages",{error:error4,params:ConversationPath,success:ListQueuedMessagesResponse})).add(HttpApiEndpoint4.patch("updateQueuedMessage","/chat/conversations/:conversationId/queued-messages/:queuedMessageId",{error:error4,params:QueuedMessagePath,payload:UpdateQueuedMessageRequest,success:QueuedMessageSchema})).add(HttpApiEndpoint4.delete("removeQueuedMessage","/chat/conversations/:conversationId/queued-messages/:queuedMessageId",{error:error4,params:QueuedMessagePath,query:RemoveQueuedMessageQuery,success:HttpApiSchema4.NoContent})).add(HttpApiEndpoint4.get("getPlaceContext","/chat/place-context",{error:error4,success:PlaceContextSchema})).add(HttpApiEndpoint4.get("getCompaction","/chat/conversations/:conversationId/compaction",{error:error4,params:ConversationPath,success:CompactionResponse})).add(HttpApiEndpoint4.post("compact","/chat/conversations/:conversationId/compactions",{error:error4,params:ConversationPath,success:CompactionResponse})).add(HttpApiEndpoint4.post("regenerateCompaction","/chat/conversations/:conversationId/compactions/regenerate",{error:error4,params:ConversationPath,success:CompactionResponse})).add(HttpApiEndpoint4.delete("resetCompaction","/chat/conversations/:conversationId/compactions/active",{error:error4,params:ConversationPath,success:CompactionResponse})).add(HttpApiEndpoint4.post("resolveEvidenceNavigation","/chat/invocations/:invocationId/evidence-navigation",{error:error4,params:EvidenceNavigationPath,payload:EvidenceNavigationRequest,success:EvidenceNavigationResponse})).add(HttpApiEndpoint4.get("getArtifactProgress","/chat/conversations/:conversationId/artifact-progress",{error:error4,params:ConversationPath,success:ArtifactProgress})){}import*as Effect2 from"effect/Effect";import*as Equal from"effect/Equal";import{HttpClient,HttpClientResponse}from"effect/http";import{HttpApi,HttpApiClient}from"effect/http-api";import*as Option from"effect/Option";import{Multipart as Multipart2}from"effect/http";import{HttpApiEndpoint as HttpApiEndpoint5,HttpApiGroup as HttpApiGroup5,HttpApiSchema as HttpApiSchema5}from"effect/http-api";import*as Schema12 from"effect/Schema";var ProjectName=Schema12.Trim.check(Schema12.isMinLength(1),Schema12.isMaxLength(200));var ProjectInstructions=Schema12.String.check(Schema12.isMaxLength(8000));var ProjectPath=Schema12.Struct({projectId:ProjectId2});var ProjectCreateRequest=Schema12.Struct({name:ProjectName});var ProjectUpdateRequest=Schema12.Struct({instructions:Schema12.optionalKey(Schema12.NullOr(ProjectInstructions)),name:Schema12.optionalKey(ProjectName)});var ProjectSchema=Schema12.Struct({createdAt:Schema12.Date,id:ProjectId2,instructions:Schema12.NullOr(Schema12.String),name:Schema12.String,updatedAt:Schema12.Date});var ProjectList=Schema12.Struct({data:Schema12.Array(ProjectSchema)});var ProjectFilePath=Schema12.Struct({fileId:ProjectFileId2,projectId:ProjectId2});var ProjectFileSchema=Schema12.Struct({contentType:Schema12.NullOr(Schema12.String),createdAt:Schema12.Date,extractionState:Schema12.Literals(["available","truncated","failed"]),filename:Schema12.String,id:ProjectFileId2,inContext:Schema12.Boolean,sizeBytes:Schema12.Int});var ProjectFileList=Schema12.Struct({files:Schema12.Array(ProjectFileSchema),maxCharacters:Schema12.Int,usedCharacters:Schema12.Int});var ProjectFileUpload=Schema12.Struct({file:Multipart2.SingleFileSchema}).pipe(HttpApiSchema5.asMultipart({maxFileSize:maxUploadPartBytes,maxParts:1}));var error5=chatFailures;class ChatProjectsApi2 extends HttpApiGroup5.make("chatProjects").add(HttpApiEndpoint5.get("listProjects","/chat/projects",{error:error5,success:ProjectList})).add(HttpApiEndpoint5.post("createProject","/chat/projects",{error:error5,payload:ProjectCreateRequest,success:ProjectSchema.pipe(HttpApiSchema5.status(201))})).add(HttpApiEndpoint5.patch("updateProject","/chat/projects/:projectId",{error:error5,params:ProjectPath,payload:ProjectUpdateRequest,success:ProjectSchema})).add(HttpApiEndpoint5.delete("deleteProject","/chat/projects/:projectId",{error:error5,params:ProjectPath,success:HttpApiSchema5.NoContent})).add(HttpApiEndpoint5.get("listProjectFiles","/chat/projects/:projectId/files",{error:error5,params:ProjectPath,success:ProjectFileList})).add(HttpApiEndpoint5.post("uploadProjectFile","/chat/projects/:projectId/files",{error:error5,params:ProjectPath,payload:ProjectFileUpload,success:ProjectFileSchema.pipe(HttpApiSchema5.status(201))})).add(HttpApiEndpoint5.delete("deleteProjectFile","/chat/projects/:projectId/files/:fileId",{error:error5,params:ProjectFilePath,success:HttpApiSchema5.NoContent})).add(HttpApiEndpoint5.get("getProjectFileDownloadUrl","/chat/projects/:projectId/files/:fileId/download-url",{error:error5,params:ProjectFilePath,success:DownloadUrl})){}import{HttpApiEndpoint as HttpApiEndpoint6,HttpApiGroup as HttpApiGroup6}from"effect/http-api";import*as Schema13 from"effect/Schema";var maxClipBytes=25*1024*1024;var ClipContentType=Schema13.String.check(Schema13.isMaxLength(255),Schema13.isPattern(/^audio\/[a-z0-9][a-z0-9!#$&^_.+-]*(?:\s*;.*)?$/iu));var CreateSpeechClipRequest=Schema13.Struct({contentType:ClipContentType,size:Schema13.Int.check(Schema13.isBetween({maximum:maxClipBytes,minimum:1}))});var SpeechClipUpload=Schema13.Struct({clipId:SpeechClipId2,headers:Schema13.Record(Schema13.String,Schema13.String),method:Schema13.Literal("PUT"),url:Schema13.String});var TranscribeSpeechClipRequest=Schema13.Struct({clipId:SpeechClipId2});var SpeechTranscription=Schema13.Struct({text:Schema13.String});var ReadAloudPartPath=Schema13.Struct({invocationId:InvocationId2,partIndex:Schema13.NumberFromString.pipe(Schema13.check(Schema13.isInt(),Schema13.isGreaterThanOrEqualTo(0),Schema13.isLessThanOrEqualTo(1e4)))});var ReadAloudPart=Schema13.Struct({partCount:Schema13.Int,url:Schema13.String});var SpeechAvailability=Schema13.Struct({readAloud:Schema13.Boolean,remoteTranscription:Schema13.Boolean});var error6=chatFailures;class ChatSpeechApi2 extends HttpApiGroup6.make("chatSpeech").add(HttpApiEndpoint6.post("createSpeechClip","/chat/speech/clips",{error:error6,payload:CreateSpeechClipRequest,success:SpeechClipUpload})).add(HttpApiEndpoint6.post("transcribeSpeechClip","/chat/speech/transcriptions",{error:error6,payload:TranscribeSpeechClipRequest,success:SpeechTranscription})).add(HttpApiEndpoint6.get("getReadAloudPart","/chat/speech/read-aloud/:invocationId/parts/:partIndex",{error:error6,params:ReadAloudPartPath,success:ReadAloudPart})).add(HttpApiEndpoint6.get("getSpeechAvailability","/chat/speech/availability",{error:error6,success:SpeechAvailability})){}class ChatSurfaceApi2 extends HttpApi.make("chat-surface").add(ChatApi2).add(ChatProjectsApi2).add(ChatAttachmentsApi2).add(ChatSpeechApi2).add(ChatFeedbackApi2).add(ChatCatalogApi2){}var responsesByReference=(client)=>HttpClient.tap(client,(response)=>Effect2.sync(()=>{Equal.byReferenceUnsafe(response);const source=HttpClientResponse.toWeb(response);if(Option.isSome(source)){Equal.byReferenceUnsafe(source.value)}}));var makeChatSurfaceClient2=({transformClient,...options})=>HttpApiClient.make(ChatSurfaceApi2,{...options,transformClient:(client)=>responsesByReference(transformClient?.(client)??client)});
|
|
2
|
-
export{chatRefusalReasons2,chatConflictReasons2,uploadRejectionReasons2,ChatAttachmentsApi2,ChatCatalogApi2,ChatFeedbackApi2,TranscriptSchema2,ChatApi2,ChatProjectsApi2,ChatSpeechApi2,ChatSurfaceApi2,makeChatSurfaceClient2};
|
package/dist/domain-tg4azwc2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{makeChatSurfaceClient2}from"./domain-8rwbw2ah.js";import{AgentId2}from"./domain-5fpd4fte.js";import{ciDataPartSchemas2}from"./domain-50vzrrp9.js";import{displayPartEvidence2,evidencePartId2,ciMessageMetadataSchema2,hasObjectRuntimeKind2,hasStringRuntimeKind2,asRuntimeValue2}from"./domain-54qeg701.js";import{aiErrorCodes2,AiFailureError2}from"./domain-9wzbv87n.js";import{createContext,useContext,useEffect,useMemo,useRef,useState,useSyncExternalStore}from"react";var sameItems=(left,right)=>left.length===right.length&&left.every((item,at)=>item===right[at]);var takesLaunches=({receive})=>receive!==undefined;var retryPause=(attempt)=>Math.min(1000*2**attempt,30000);var pause=async(milliseconds,signal)=>{if(signal.aborted){return}await new Promise((resolve)=>{const timeout=globalThis.setTimeout(resolve,milliseconds);signal.addEventListener("abort",()=>{globalThis.clearTimeout(timeout);resolve()},{once:true})})};var waitAnswer=async(intents,handle,signal)=>{try{return await intents.call("wait",{handle},{signal})}catch{return}};var followRun=async(intents,handle,signal)=>{for(let attempt=0;!signal.aborted;attempt+=1){const answer=await waitAnswer(intents,handle,signal);if(answer!==undefined&&(answer.ok||!answer.error.retryable)){return signal.aborted?undefined:answer}await pause(retryPause(attempt),signal)}return};var createPageRegistry=()=>{const root={parent:undefined};const subscribers=new Set;const listeners=new Set;const running=new Map;const lookups=new WeakMap;let registered=[];let version=0;let waits=[];let shown=[];let adoptions=[];let connection;let fallback;const changed=()=>{for(const onChange of subscribers){onChange()}};const publish=(notice)=>{for(const{fqn,listener}of listeners){if(fqn===notice.fqn){listener(notice)}}};const persist=()=>{connection?.waits?.write(waits)};const drop=(handle)=>{running.delete(handle);waits=waits.filter((wait)=>wait.handle!==handle);persist()};const show=(notice)=>{shown=[...shown.filter(({id})=>id!==notice.id),notice];changed()};const follow=async(wait,intents)=>{const controller=new AbortController;running.set(wait.handle,controller);const answer=await followRun(intents,wait.handle,controller.signal);if(answer===undefined){return}if(!answer.ok){if(answer.error.code==="not_found"){drop(wait.handle)}else{running.delete(wait.handle)}return}const outcome=answer.value;const{displayName,fqn,handle}=wait;drop(handle);show({displayName,fqn,id:handle,outcome});publish({fqn,handle,outcome})};const followAdoption=async(adoption,intents)=>{const stop=new AbortController;adoption.stop=stop;const{fqn,handle}=adoption.returned;const answer=await followRun(intents,handle,stop.signal);if(answer===undefined){return}if(!answer.ok){if(answer.error.code==="not_found"){adoptions=adoptions.filter((other)=>other!==adoption)}else{adoption.stop=undefined}return}adoption.end={fqn,handle,outcome:answer.value};changed();publish(adoption.end)};const startAdoption=(adoption)=>{const intents=connection?.api;if(intents!==undefined&&adoption.stop===undefined){followAdoption(adoption,intents)}};const piecesOf=(scope,kind)=>{const byKind=lookups.get(scope)??new Map;lookups.set(scope,byKind);const cached=byKind.get(kind);if(cached?.version===version){return cached.pieces}const found=[];for(let at=scope;at;at=at.parent){for(const entry of registered){if(entry.scope===at&&entry.piece.kind===kind){found.push(entry.piece)}}}const pieces=cached!==undefined&&sameItems(cached.pieces,found)?cached.pieces:found;byKind.set(kind,{pieces,version});return pieces};const start=(wait)=>{const intents=connection?.api;if(intents!==undefined&&!running.has(wait.handle)){follow(wait,intents)}};return{adopt:(returned)=>{const adoption={end:undefined,returned,stop:undefined};adoptions=[adoption,...adoptions];startAdoption(adoption);return()=>{adoption.stop?.abort();adoptions=adoptions.filter((other)=>other!==adoption);if(adoption.end!==undefined){changed()}}},adopted:(fqn)=>adoptions.find(({end})=>end?.fqn===fqn)?.end,connect:(next)=>{connection=next;fallback=next.launchFallback===undefined?undefined:{id:"host",kind:"chat",preferred:false,receive:next.launchFallback};changed();waits=next.waits?.read()??waits;for(const wait of waits){start(wait)}for(const adoption of adoptions){startAdoption(adoption)}return()=>{connection=undefined;fallback=undefined;changed();for(const controller of running.values()){controller.abort()}running.clear();for(const adoption of adoptions){if(adoption.end===undefined){adoption.stop?.abort();adoption.stop=undefined}}}},dismiss:(id)=>{shown=shown.filter((notice)=>notice.id!==id);changed()},keep:(wait)=>{if(waits.some(({handle})=>handle===wait.handle)){return}waits=[...waits,wait];persist();start(wait)},launchTarget:(scope,target)=>{const chats=registered.map(({piece})=>piece).filter((piece)=>piece.kind==="chat"&&takesLaunches(piece));return chats.find(({id})=>id===target)??chats.find(({preferred})=>preferred)??piecesOf(scope,"chat").find(takesLaunches)??fallback},listen:(fqn,listener)=>{const entry={fqn,listener};listeners.add(entry);for(const{end}of adoptions){if(end?.fqn===fqn){listener(end)}}return()=>{listeners.delete(entry)}},notices:()=>shown,pieces:piecesOf,publish,register:(scope,piece)=>{const entry={piece,scope};registered=[...registered,entry];version+=1;changed();return()=>{registered=registered.filter((other)=>other!==entry);version+=1;changed()}},root,show,subscribe:(onChange)=>{subscribers.add(onChange);return()=>{subscribers.delete(onChange)}}}};import{jsx}from"react/jsx-runtime";var IntentsContext=createContext(undefined);var useIntentsScope2=()=>{const scope=useContext(IntentsContext);if(scope===undefined){throw new Error("Render the Intent controls and hooks inside <IntentsProvider>.")}return scope};var useOptionalIntentsScope2=()=>useContext(IntentsContext);var apiScopes=new WeakMap;var apiCount=0;var apiScopeOf=(api)=>{const known=apiScopes.get(api);if(known!==undefined){return known}apiCount+=1;const scope=`api:${apiCount}`;apiScopes.set(api,scope);return scope};var cacheScopeOf=(api,caller)=>{const apiScope=api===undefined?"none":apiScopeOf(api);return caller===undefined?apiScope:`${apiScope}:caller:${caller}`};var IntentsProvider2=({access,api,caller,children,launchFallback,waits})=>{const[owned,setOwned]=useState(()=>({caller,registry:createPageRegistry()}));if(owned.caller!==caller){setOwned({caller,registry:createPageRegistry()})}const{registry}=owned;useEffect(()=>registry.connect({api,launchFallback,waits}),[api,launchFallback,registry,waits]);const value=useMemo(()=>({access,api,cacheScope:cacheScopeOf(api,caller),registry,scope:registry.root}),[access,api,caller,registry]);return jsx(IntentsContext.Provider,{value,children})};var IntentsRegistryScope2=({children})=>{const parent=useIntentsScope2();const value=useMemo(()=>({...parent,scope:{parent:parent.scope}}),[parent]);return jsx(IntentsContext.Provider,{value,children})};var useRegisterPieceIn=(intents,{id,kind,preferred=false,receive})=>{const{registry,scope}=intents??{};const latest=useRef(receive);useEffect(()=>{latest.current=receive});const receives=receive!==undefined;useEffect(()=>registry===undefined||scope===undefined?undefined:registry.register(scope,{id,kind,preferred,receive:receives?(launch)=>{latest.current?.(launch)}:undefined}),[id,kind,preferred,receives,registry,scope])};var useRegisterPiece2=(registration)=>{useRegisterPieceIn(useIntentsScope2(),registration)};var useRegisterOptionalPiece=(registration)=>{useRegisterPieceIn(useOptionalIntentsScope2(),registration)};var usePieces2=(kind)=>{const{registry,scope}=useIntentsScope2();return useSyncExternalStore(registry.subscribe,()=>registry.pieces(scope,kind),()=>registry.pieces(scope,kind))};var useIntentResult2=(fqn,listener)=>{const{registry}=useIntentsScope2();const latest=useRef(listener);useEffect(()=>{latest.current=listener});useEffect(()=>registry.listen(fqn,(notice)=>{latest.current(notice)}),[fqn,registry])};var chatBlockedKinds2=["sign_in_to_chat","chat_not_available","app_not_available","service_not_available"];var chatBlockedState=(error,read)=>{if(error.code==="unauthenticated"){return{error,kind:"sign_in_to_chat"}}if(error.code==="forbidden"&&error.reason==="capability_missing"){return{error,kind:"chat_not_available"}}if(error.code==="forbidden"&&error.reason==="app_disabled"){return{error,kind:"app_not_available"}}if(read==="first"&&(error.code==="unavailable"||error.code==="internal")){return{error,kind:"service_not_available"}}return null};import{useChat}from"@ai-sdk/react";import{useActorRef,useSelector}from"@xstate/react";import*as Effect3 from"effect/Effect";import{createContext as createContext2,useCallback,useContext as useContext2,useEffect as useEffect2,useMemo as useMemo2,useState as useState2,useSyncExternalStore as useSyncExternalStore2}from"react";import*as Context from"effect/Context";import*as Duration from"effect/Duration";import*as Effect from"effect/Effect";import{FetchHttpClient,HttpClientError}from"effect/http";import*as Layer from"effect/Layer";import*as ManagedRuntime from"effect/ManagedRuntime";import*as Option from"effect/Option";import*as Schedule from"effect/Schedule";import*as Schema from"effect/Schema";class ChatSurface extends Context.Service()("@collective-intelligence/ai/headless/ChatSurface"){}var platformFetch=(fetch)=>Object.assign((input,init)=>fetch(input,init),{preconnect:()=>null});var chatSurfaceLayer=({fetch,...client})=>{const http=fetch===undefined?FetchHttpClient.layer:FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch)(platformFetch(fetch))));return Layer.effect(ChatSurface)(makeChatSurfaceClient2(client)).pipe(Layer.provide(http))};var makeChatSessionRuntime=(options)=>ManagedRuntime.make(chatSurfaceLayer(options));var decodeEnvelope=Schema.decodeUnknownOption(Schema.Struct({error:Schema.Struct({code:Schema.Literals(aiErrorCodes2),details:Schema.optionalKey(Schema.Struct({reason:Schema.optionalKey(Schema.String)})),message:Schema.String,retryable:Schema.Boolean})}));var codeOfStatus=(status)=>{if(status===401){return"unauthenticated"}if(status===403){return"forbidden"}if(status===404){return"not_found"}if(status===409){return"conflict"}if(status===429){return"rate_limited"}if(status>=500){return"unavailable"}return"invalid_request"};var clientFailure=(failure)=>{const{reason}=failure;if(reason._tag==="TransportError"){return{code:"unavailable",message:failure.message,retryable:true}}if(reason._tag==="StatusCodeError"){const code=codeOfStatus(reason.response.status);return{code,message:failure.message,retryable:code==="rate_limited"||code==="unavailable"}}return{code:"internal",message:failure.message,retryable:false}};var toSessionFailure=(cause)=>{if(cause instanceof AiFailureError2){return cause}if(HttpClientError.isHttpClientError(cause)){return new AiFailureError2(clientFailure(cause),{cause})}return Option.match(decodeEnvelope(cause),{onNone:()=>new AiFailureError2({code:"internal",message:cause instanceof Error?cause.message:String(cause),retryable:false},{cause}),onSome:({error})=>{const failure={code:error.code,message:error.message,retryable:error.retryable};const reason=error.details?.reason;return new AiFailureError2(reason===undefined?failure:{...failure,reason},{cause})}})};var callChatSurface=(operation)=>Effect.gen(function*call(){const client=yield*ChatSurface;return yield*operation(client).pipe(Effect.mapError(toSessionFailure),Effect.catchDefect((defect)=>Effect.fail(toSessionFailure(defect))))});var retryRead=(read)=>Effect.retry(read,{schedule:Schedule.exponential(Duration.millis(100)),times:3,while:(failure)=>failure.error.retryable});var retryWatch=(watch)=>Effect.retry(watch,{schedule:Schedule.min([Schedule.exponential(Duration.millis(100)),Schedule.spaced(Duration.seconds(5))]),while:(failure)=>failure.error.retryable});var chatFeatureFlags2={memory:"memory",projects:"projects"};var chatControls=(host)=>{const isOn=(flag)=>host.flags?.isEnabled(flag)??true;return{files:host.files,memory:isOn(chatFeatureFlags2.memory),openTarget:host.openTarget,projects:isOn(chatFeatureFlags2.projects),trail:host.trail,voiceInput:host.speechInput}};var createBrowserFilePort2=()=>({download:(file)=>{const link=document.createElement("a");link.href=file.url;link.download=file.filename;link.rel="noopener";document.body.append(link);link.click();link.remove();return Promise.resolve()},open:(file)=>{window.open(file.url,"_blank","noopener");return Promise.resolve()}});var endedCards=(messages)=>messages.flatMap(({parts})=>parts.flatMap((part)=>part.type==="data-intent-card"&&(part.data.state==="completed"||part.data.state==="failed")?[part.data]:[]));var intentCardReloadMs=5000;var intentCardPending=(messages)=>messages.some(({parts})=>parts.some((part)=>part.type==="data-intent-card"&&part.data.state==="running"));var noticeOf=(card)=>({fqn:card.fqn,handle:card.dispatchId,outcome:card.state==="completed"?{kind:"completed",result:card.result}:{kind:"failed",reason:card.reason}});var createIntentCardEndTracker=()=>{let known;return{observe:(status,messages)=>{if(status!=="ready"){known=undefined;return[]}const ended=endedCards(messages);if(known===undefined){known=new Set(ended.map(({dispatchId})=>dispatchId));return[]}const seen=known;const fresh=ended.filter(({dispatchId})=>!seen.has(dispatchId));for(const{dispatchId}of fresh){seen.add(dispatchId)}return fresh.map(noticeOf)}}};import{fromEffect}from"@collective-intelligence/effect-xstate/actors";import{isToolUIPart}from"ai";import{SecureRandom}from"effect/crypto";import*as Effect2 from"effect/Effect";import{assign,enqueueActions,fromCallback,raise,setup}from"xstate";import{Chat}from"@ai-sdk/react";import{lastAssistantMessageIsCompleteWithApprovalResponses}from"ai";import*as Option3 from"effect/Option";import*as Schema4 from"effect/Schema";import*as Schema3 from"effect/Schema";import*as Option2 from"effect/Option";import*as Schema2 from"effect/Schema";var openRunStates2=["pending","running","resuming","paused","reconciliation_required","waiting_for_approval","waiting_for_input","waiting_for_permission"];var endedRunStates=["completed","cancelled","error","failed"];var open=new Set(openRunStates2);var isOpenRunState2=(state)=>open.has(state);var decodeRunState=Schema2.decodeUnknownOption(Schema2.Literals([...openRunStates2,...endedRunStates]));var runStateOf=(status)=>Option2.getOrNull(decodeRunState(status));var isOpen=(status)=>{const state=runStateOf(status);return state!==null&&isOpenRunState2(state)};var openTurnOf=({messages})=>{const newest=messages.at(-1);if(newest===undefined){return null}return newest.role==="user"||isOpen(newest.run?.status??newest.status)?{invocationId:newest.invocationId}:null};var openAgentTurnOf=({agentTurns})=>agentTurns.at(-1)?.status==="pending"?{invocationId:null}:null;var textParts=(text)=>text===""?[]:[{text,type:"text"}];var unknownMediaType="application/octet-stream";var attachmentParts=(message)=>message.attachments.map((attachment)=>({filename:attachment.filename,mediaType:attachment.contentType??unknownMediaType,type:"file",url:attachment.mediaUrl??""}));var answerMetadata=(message)=>({invocationId:message.invocationId,...message.currentUserFeedback!==undefined&&{currentUserFeedback:message.currentUserFeedback},...message.feedbackTargetId!==undefined&&{feedbackTargetId:message.feedbackTargetId},...message.run?.traceLink!==undefined&&{traceLink:message.run.traceLink}});var steeringParts=(transcript,invocationId)=>transcript.steeringMessages.filter((steering)=>steering.invocationId===invocationId).map((steering)=>({id:steering.id,parts:[{text:steering.content,type:"text"}],type:"steering-message"}));var isMemoryEvent=Schema3.is(ciDataPartSchemas2["memory-evidence"].fields.events.value);var memoryParts=(invocationId,run)=>{const events=(run?.memoryEvidence?.events??[]).flatMap((event)=>{const shown={category:event.category,kind:event.kind,lifecycleStatus:event.lifecycleStatus,memoryId:event.memoryId,reason:event.reason,scope:event.scope};return isMemoryEvent(shown)?[shown]:[]});return events.length===0?[]:[{data:{events},id:`memory-evidence-${invocationId}`,type:"data-memory-evidence"}]};var imageParts=(invocationId,run)=>(run?.toolTrace??[]).flatMap((trace,traceIndex)=>trace.displayParts.flatMap((part,partIndex)=>part.type==="image_generation"?[{input:{},output:part.data,state:"output-available",toolCallId:`image-generation-${invocationId}-${traceIndex}-${partIndex}`,toolName:trace.fqn??trace.displayName??"image_generation",type:"dynamic-tool"}]:[]));var evidenceParts=(invocationId,run)=>(run?.toolTrace??[]).flatMap((trace,traceIndex)=>trace.displayParts.flatMap((part,partIndex)=>{const evidence=displayPartEvidence2(part);const toolCallId=trace.toolCallId??`${invocationId}-${traceIndex}`;return evidence===undefined?[]:[{data:evidence,id:evidencePartId2(toolCallId,partIndex),type:"data-evidence"}]}));var intentCardParts=(cards)=>(cards??[]).map((card)=>({data:card,id:`intent-card-${card.dispatchId}`,type:"data-intent-card"}));var agentTurnMessages=(turn)=>{const parts=[...textParts(turn.message??""),...intentCardParts(turn.intentCards)];return[{id:`user-${turn.turnId}`,parts:textParts(turn.input),role:"user"},...turn.message===null&&parts.length===0?[]:[{id:turn.turnId,parts,role:"assistant"}]]};var conversationMessages=(transcript)=>{if(transcript.conversation.agent!==null){return{messages:transcript.agentTurns.flatMap(agentTurnMessages),openTurn:openAgentTurnOf(transcript)}}const openTurn=openTurnOf(transcript);const messages=transcript.messages.flatMap((message)=>{if(message.role==="user"){return[{id:`user-${message.invocationId}`,metadata:{invocationId:message.invocationId,...message.contextTrail!==undefined&&{turnOptions:{contextTrail:message.contextTrail}}},parts:[...attachmentParts(message),...textParts(message.content)],role:"user"}]}if(message.invocationId===openTurn?.invocationId){return[]}return[{id:message.invocationId,metadata:answerMetadata(message),parts:[...steeringParts(transcript,message.invocationId),...imageParts(message.invocationId,message.run),...evidenceParts(message.invocationId,message.run),...textParts(message.content),...intentCardParts(message.run?.intentCards),...memoryParts(message.invocationId,message.run)],role:"assistant"}]});return{messages,openTurn}};var sentFileParts=(files,uploaded)=>uploaded.flatMap(({contentType,filename},index)=>{const file=files[index];return file===undefined?[]:[{filename,mediaType:contentType??(file.type===""?unknownMediaType:file.type),type:"file",url:URL.createObjectURL(file)}]});var revokeSentFiles=(messages)=>{for(const{parts}of messages){for(const part of parts){if(part.type==="file"&&part.url.startsWith("blob:")){URL.revokeObjectURL(part.url)}}}};var newChatId="new-chat";var decodeMetadata=Schema4.decodeUnknownOption(ciMessageMetadataSchema2);var namedTurnOf=(chunk)=>chunk.type==="start"?Option3.getOrUndefined(decodeMetadata(chunk.messageMetadata))?.invocationId:undefined;var watched=(stream,{finish,named})=>{finish.finishReason="none";return stream.pipeThrough(new TransformStream({transform:(chunk,controller)=>{if(chunk.type==="finish"){finish.finishReason=chunk.finishReason??"stop"}controller.enqueue(chunk);const invocationId=namedTurnOf(chunk);if(invocationId!==undefined){named(invocationId)}}}))};var isNetworkFailure=(error)=>{if(!(error instanceof TypeError)){return false}const message=error.message.toLowerCase();return message.includes("fetch")||message.includes("network")||message==="load failed"};var networkFailureOf=(failure)=>{const cause=failure instanceof AiFailureError2?failure.cause:failure;return cause instanceof TypeError&&isNetworkFailure(cause)?cause:null};var watchedTransport=(transport,watch)=>({onResumeEmpty:transport.onResumeEmpty,reconnectToStream:async(request)=>{const stream=await transport.reconnectToStream(request);return stream===null?null:watched(stream,watch)},resumeStreamIsReplay:transport.resumeStreamIsReplay??false,sendMessages:async(request)=>{try{return watched(await transport.sendMessages(request),watch)}catch(error){throw networkFailureOf(error)??error}}});var streamEnd=({isAbort,isDisconnect,isError},{finishReason})=>{if(isAbort){return"stopped"}if(isDisconnect){return"disconnected"}if(isError){return"failed"}return finishReason==="none"||finishReason==="interrupted"?"cut":"ended"};var errorOf=(error)=>{if(error instanceof AiFailureError2){return error.error}return isNetworkFailure(error)?{code:"unavailable",message:error.message,retryable:true}:{code:"internal",message:error.message,retryable:false}};var makeChatRegistry=(transport)=>{const chats=new Map;const listeners=new Set;const tell=(event)=>{for(const listener of listeners){listener(event)}};const make=(conversationId)=>{const finish={finishReason:"none"};const chat=new Chat({dataPartSchemas:ciDataPartSchemas2,id:conversationId??newChatId,messageMetadataSchema:ciMessageMetadataSchema2,onData:(part)=>{if(conversationId!==null&&part.type==="data-run-status"){tell({conversationId,runStatus:part.data,type:"chat.run_status"})}},onError:(error)=>{if(conversationId!==null){tell({conversationId,dropped:isNetworkFailure(error),error:errorOf(error),type:"chat.failed"})}},onFinish:(options)=>{if(conversationId!==null){tell({conversationId,end:streamEnd(options,finish),type:"chat.finished"})}},sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithApprovalResponses,transport:watchedTransport(transport,{finish,named:(invocationId)=>{if(conversationId!==null){tell({conversationId,invocationId,type:"chat.turn_named"})}}})});chats.set(conversationId??newChatId,chat);return chat};return{chat:(conversationId)=>chats.get(conversationId??newChatId)??make(conversationId),dispose:()=>{for(const chat of chats.values()){chat.stop();revokeSentFiles(chat.messages)}chats.clear()},subscribe:(listener)=>{listeners.add(listener);return()=>{listeners.delete(listener)}}}};import*as DateTime from"effect/DateTime";var trailBufferSize2=50;var isMetadata=(entry)=>("source"in entry)&&!("event"in entry);var createTrailBuffer2=(now=()=>DateTime.formatIso(DateTime.nowUnsafe()))=>{const subscribers=new Set;const metadataKeys=new Map;let entries=[];let latestVisit;let recording=false;const notify=()=>{for(const onChange of subscribers){onChange()}};const commit=(next)=>{let kept=next;while(kept.length>trailBufferSize2){const oldest=kept.findIndex((entry)=>!isMetadata(entry));const dropped=oldest===-1?0:oldest;kept=kept.filter((_,at)=>at!==dropped)}entries=kept;notify()};const withoutMetadataOf=(source)=>entries.filter((entry)=>!isMetadata(entry)||entry.source!==source);return{clearMetadata:(source)=>{if(!metadataKeys.delete(source)){return}const next=withoutMetadataOf(source);if(next.length!==entries.length){commit(next)}},entries:()=>entries,pushEvent:(source,{event,...data})=>{if(recording){commit([...entries,{at:now(),data,event,source}])}},recordPageVisit:({app,page,title})=>{if(!recording){return}const latest=latestVisit;if(latest?.app===app&&latest.page===page){if(latest.title===title){return}const retitled={...latest,title};latestVisit=retitled;if(entries.includes(latest)){commit(entries.map((entry)=>entry===latest?retitled:entry))}return}const visit={app,at:now(),page,title};latestVisit=visit;commit([...entries,visit])},recording:()=>recording,remove:(entry)=>{if(entries.includes(entry)){commit(entries.filter((other)=>other!==entry))}},setMetadata:(source,data)=>{if(!recording){return}const key=JSON.stringify(data);if(metadataKeys.get(source)===key){return}metadataKeys.set(source,key);commit([...withoutMetadataOf(source),{at:now(),data,source}])},setRecording:(enabled)=>{if(enabled===recording){return}recording=enabled;if(!enabled){metadataKeys.clear();latestVisit=undefined;entries=[]}notify()},subscribe:(onChange)=>{subscribers.add(onChange);return()=>{subscribers.delete(onChange)}}}};var turnTrail2=(trail,launched=[])=>{if(trail===undefined||!trail.recording()){return}const entries=launched.length===0?trail.entries():[...trail.entries(),...launched];return entries.length===0?undefined:entries};var noFollow={invocationId:null,joined:false,next:null};var userMessageCount=(messages)=>messages.filter(({role})=>role==="user").length;var turnEnded="turn_ended";var answeredEndedTurn=({code,reason})=>code==="conflict"&&reason===turnEnded;var refusal=(message)=>({code:"invalid_request",message,retryable:false});var noOpenConversation=refusal("No Conversation is open.");var runningAnswerTakesNoFiles=refusal("A message to a running answer takes no attachments.");var noRunningTurn=refusal("The running answer has no turn id yet.");var composerBusy=refusal("The last message is still on its way: send again once it has gone.");var launchIntoBusyConversation={code:"conflict",message:"Another turn of this conversation is running.",reason:"intent_turn_busy",retryable:false};var userMessage=(id,text)=>({id,parts:[{text,type:"text"}],role:"user"});var failureOf=(error)=>error instanceof AiFailureError2?error.error:{code:"internal",message:error instanceof Error?error.message:String(error),retryable:false};var blocks=(error,read)=>chatBlockedState(failureOf(error),read)!==null;var failedWith=(read)=>({event})=>{const failure=failureOf("error"in event?event.error:undefined);return{blocked:chatBlockedState(failure,read),failure}};var draftBack=({draft,sending})=>draft===""?sending:draft;var sendFailedWith=(read)=>(args)=>({...failedWith(read)(args),draft:draftBack(args.context),sending:""});var onConversation=(conversationId,operation)=>conversationId===null?Effect2.fail(new AiFailureError2(noOpenConversation)):operation(conversationId);var titleOf=(text)=>text.trim().split(/\s+/u).slice(0,6).join(" ");var uploadFiles=(conversationId,{files=[],...submit})=>{if(files.length===0){return Effect2.succeed(submit)}const payload=new FormData;for(const file of files){payload.append("files",file)}return Effect2.map(callChatSurface((client)=>client.chatAttachments.uploadAttachments({params:{conversationId},payload})),({attachments})=>({...submit,attachmentIds:[...submit.attachmentIds??[],...attachments.map(({id})=>id)],fileParts:sentFileParts(files,attachments)}))};var hasAttachments=({attachmentIds=[],files=[]})=>attachmentIds.length>0||files.length>0;var listConversations=({historyScope,subject})=>Effect2.map(callChatSurface((client)=>client.chat.listConversations({query:{...historyScope!==undefined&&{historyScope},...subject!==undefined&&{subject}}})),({data})=>data);var actors={cancelTurn:fromEffect(({invocationId})=>invocationId===null?Effect2.void:Effect2.asVoid(callChatSurface((client)=>client.chat.cancelTurn({params:{invocationId}})))),changeQueued:fromEffect(({change,conversationId})=>onConversation(conversationId,(id)=>{if(change===null){return Effect2.void}const params={conversationId:id,queuedMessageId:change.queuedMessageId};return Effect2.asVoid(change.type==="UPDATE_QUEUED"?callChatSurface((client)=>client.chat.updateQueuedMessage({params,payload:{content:change.content,revision:change.revision}})):callChatSurface((client)=>client.chat.removeQueuedMessage({params,query:{revision:change.revision}})))})),chatEvents:fromCallback(({input:{registry,transport},sendBack})=>{const stopChats=registry.subscribe(sendBack);const stopResumeEmpty=transport.onResumeEmpty(({conversationId})=>{sendBack({conversationId,type:"chat.resume_empty"})});return()=>{stopChats();stopResumeEmpty();registry.dispose()}}),createConversation:fromEffect(({newChat,submit})=>{const title=titleOf(submit.text);return Effect2.flatMap(callChatSurface((client)=>client.chat.createConversation({payload:title===""?newChat:{...newChat,title}})),(conversation)=>Effect2.match(uploadFiles(conversation.id,submit),{onFailure:({error})=>({conversation,submit,uploadFailure:error}),onSuccess:(uploaded)=>({conversation,submit:uploaded,uploadFailure:null})}))}),listConversations:fromEffect((filter)=>retryRead(listConversations(filter))),listQueued:fromEffect(({conversationId})=>onConversation(conversationId,(id)=>retryRead(Effect2.map(callChatSurface((client)=>client.chat.listQueuedMessages({params:{conversationId:id}})),({data})=>data)))),loadSession:fromEffect(({historyScope,placeContext,subject,trail})=>Effect2.all({conversations:retryRead(listConversations({historyScope,subject})),placeContext:placeContext===null?retryRead(callChatSurface((client)=>client.chat.getPlaceContext())).pipe(Effect2.tap(({contextTrailEnabled})=>Effect2.sync(()=>{trail?.setRecording(contextTrailEnabled)}))):Effect2.succeed(placeContext)},{concurrency:"unbounded"})),queueMessage:fromEffect(({conversationId,launchId,text})=>onConversation(conversationId,(id)=>{const clientMessageId=launchId??SecureRandom.uuidV4Unsafe();return Effect2.map(callChatSurface((client)=>client.chat.queueMessage({params:{conversationId:id},payload:{clientMessageId,content:text}})),(answer)=>({answer,clientMessageId,text}))})),readMessages:fromEffect(({conversationId,resume})=>onConversation(conversationId,(id)=>retryRead(Effect2.map(callChatSurface((client)=>client.chat.getTranscript({params:{conversationId:id}})),(transcript)=>({...conversationMessages(transcript),resume}))))),steer:fromEffect(({conversationId,invocationId,text})=>onConversation(conversationId,(id)=>{if(invocationId===null){return Effect2.fail(new AiFailureError2(noRunningTurn))}const clientMessageId=SecureRandom.uuidV4Unsafe();return Effect2.map(callChatSurface((client)=>client.chat.sendSteeringMessage({params:{conversationId:id},payload:{clientMessageId,content:text,invocationId}})),(answer)=>({answer,clientMessageId,text}))})),uploadFiles:fromEffect(({conversationId,submit})=>onConversation(conversationId,(id)=>uploadFiles(id,submit))),watchWait:fromEffect(({conversationId,invocationId})=>conversationId===null||invocationId===null?Effect2.void:retryWatch(callChatSurface((client)=>client.chat.watchTurnWait({params:{conversationId,invocationId}}))).pipe(Effect2.repeat({while:({waiting})=>waiting}),Effect2.asVoid))};var invocationIdOf=(invocationId)=>invocationId;var openChat=(context)=>context.registry.chat(context.conversationId);var isStreaming=(context)=>{const{status}=openChat(context);return status==="submitted"||status==="streaming"};var shownWaitOf=(context)=>{const{conversationId}=context;const newest=openChat(context).lastMessage;const invocationId=newest?.metadata?.invocationId;if(conversationId===null||isStreaming(context)||newest?.role!=="assistant"||invocationId===undefined){return null}return newest.parts.some((part)=>isToolUIPart(part)&&part.state==="approval-requested")?{conversationId,invocationId:invocationIdOf(invocationId)}:null};var turnRuns=(context)=>isStreaming(context)||context.follow.invocationId!==null;var runningTurnOf=(context)=>{if(context.follow.invocationId!==null){return context.follow.invocationId}const newest=openChat(context).lastMessage;const invocationId=newest?.role==="assistant"?newest.metadata?.invocationId:undefined;return invocationId===undefined?null:invocationIdOf(invocationId)};var namedTurnOf2=(event)=>{if(event.type==="chat.turn_named"){return invocationIdOf(event.invocationId)}return event.type==="chat.run_status"&&event.runStatus.kind==="running_turn"?invocationIdOf(event.runStatus.invocationId):null};var stopChat=({context})=>{openChat(context).stop()};var turnOptionsOf=({capabilities:chosen,host},{attachmentIds,capabilities=chosen,directTool,launch,selectedReportRunId,trail})=>{const contextTrail=turnTrail2(host.trail,trail);const choices=launch===undefined?{...directTool!==undefined&&{directTool},...capabilities.length>0&&{selectedCapabilities:capabilities.map(({id,kind})=>({id,kind}))}}:{launch};return{...attachmentIds!==undefined&&attachmentIds.length>0&&{attachmentIds:[...attachmentIds]},...contextTrail!==undefined&&{contextTrail:[...contextTrail]},...choices,...selectedReportRunId!==undefined&&{selectedReportRunId}}};var isLaunch=(event)=>event.type==="SUBMIT"&&event.launchId!==undefined;var isMessageLaunch=(event)=>isLaunch(event)&&event.type==="SUBMIT"&&event.launch===undefined&&event.capabilities===undefined&&(event.trail===undefined||event.trail.length===0);var submitOf=(event)=>{if(event.type!=="SUBMIT"){return{text:""}}const{type:_submit,...submit}=event;return submit};var resume=(context)=>{const chat=openChat(context);queueMicrotask(()=>{chat.resumeStream()})};var addUserMessage=(context,message)=>{const chat=openChat(context);if(!chat.messages.some(({id})=>id===message.id)){chat.messages=[...chat.messages,message]}};var showMessages=(context,{messages})=>{if(!isStreaming(context)){const chat=openChat(context);revokeSentFiles(chat.messages);chat.messages=messages}};var newestUserText=(context)=>{let text="";for(const{parts,role}of openChat(context).messages){if(role==="user"){text=parts.flatMap((part)=>part.type==="text"?[part.text]:[]).join("")}}return text};var afterRead=(context,{messages})=>{const{draft,dropped}=context;if(dropped===null){return{}}return userMessageCount(messages)>=dropped.userMessages?{dropped:null}:{draft:draft===""?newestUserText(context):draft,dropped:null,failure:dropped.error}};var sendThroughChat=(context,submit)=>{const turnOptions=turnOptionsOf(context,submit);const metadata=Object.keys(turnOptions).length===0?{}:{turnOptions};openChat(context).sendMessage(submit.launchId===undefined?{files:[...submit.fileParts??[]],metadata,text:submit.text}:{id:submit.launchId,metadata,parts:[{text:submit.text,type:"text"}]});const conversation=context.conversations.find(({id})=>id===context.conversationId);if(conversation!==undefined){context.host.messages?.sent({conversation})}};var answerFollowOf=({answer,clientMessageId,text},streaming)=>{switch(answer.outcome){case"queued":{return{reloadQueue:true,resume:false,started:null}}case"started":{return{reloadQueue:true,resume:true,started:{invocationId:answer.invocationId??null,message:userMessage(clientMessageId,text)}}}default:{const state="status"in answer?runStateOf(answer.status):"running";return{reloadQueue:false,resume:!streaming&&state!==null&&isOpenRunState2(state),started:null}}}};var isSelected=(context,conversationId)=>context.conversationId===conversationId;var chatSessionMachine=setup({actions:{followSent:enqueueActions(({context,enqueue},sent)=>{const streaming=isStreaming(context);const follow=answerFollowOf(sent,streaming);const{started}=follow;if(started!==null&&streaming){enqueue.assign({follow:{...context.follow,next:{invocationId:started.invocationId,userMessage:started.message}}})}else if(started!==null){enqueue(()=>{addUserMessage(context,started.message);resume(context)});enqueue.assign({follow:{...noFollow,invocationId:started.invocationId}})}else if(follow.resume){enqueue(()=>{resume(context)})}if(follow.reloadQueue){enqueue.raise({type:"RELOAD_QUEUE"})}}),takeDraft:assign(({event})=>({draft:"",sending:event.type==="SUBMIT"||event.type==="QUEUE"?event.text:""}))},actors,types:{context:{},events:{},input:{}}}).createMachine({context:({input})=>{const host=input.host??{};return{blocked:null,capabilities:[],conversationId:host.sessions?.read(input.place)?.conversationId??null,conversations:[],draft:"",dropped:null,failure:null,follow:noFollow,historyScope:input.historyScope,host,newChat:{},place:input.place,placeContext:null,queuedMessages:[],registry:makeChatRegistry(input.transport),runtime:makeChatSessionRuntime(input.api),sending:"",subject:input.subject,transport:input.transport}},id:"chatSession",initial:"starting",invoke:{input:({context})=>({registry:context.registry,transport:context.transport}),src:"chatEvents"},on:{DRAFT:{actions:assign({draft:({event})=>event.text})},SET_CAPABILITIES:{actions:assign({capabilities:({event})=>event.capabilities})}},states:{blocked:{on:{RETRY:{actions:assign({blocked:null,failure:null}),target:"starting"}}},ready:{on:{NEW_CHAT:{actions:[assign({capabilities:[],conversationId:null,dropped:null,follow:noFollow,newChat:({event})=>{const{type:_newChat,...newChat}=event;return newChat},queuedMessages:[]}),({context})=>{context.host.sessions?.write(context.place,{conversationId:null})}],reenter:true,target:"ready"},RETRY:{actions:[assign({failure:null}),raise({type:"RELOAD_CONVERSATIONS"}),raise({type:"RELOAD_QUEUE"})]},SELECT_CONVERSATION:{actions:[assign({capabilities:[],conversationId:({event})=>event.conversationId,dropped:null,follow:noFollow,queuedMessages:[]}),({context,event})=>{context.host.sessions?.write(context.place,{conversationId:event.conversationId})}],target:"switching"},"chat.failed":[{actions:assign({dropped:({context,event})=>({error:event.error,userMessages:userMessageCount(openChat(context).messages)})}),guard:({context,event})=>isSelected(context,event.conversationId)&&event.dropped},{actions:raise({resume:false,type:"READ_MESSAGES"}),guard:({context,event})=>isSelected(context,event.conversationId)&&answeredEndedTurn(event.error)},{actions:assign(failedWith("later")),guard:({context,event})=>isSelected(context,event.conversationId)&&chatBlockedState(event.error,"later")!==null,target:"blocked"},{actions:assign({failure:({event})=>event.error}),guard:({context,event})=>isSelected(context,event.conversationId)}],"chat.finished":[{actions:[({context})=>{const{next}=context.follow;if(next!==null){addUserMessage(context,next.userMessage);resume(context)}},assign({follow:({context})=>({...noFollow,invocationId:context.follow.next?.invocationId??null})}),raise({type:"RELOAD_QUEUE"})],guard:({context,event})=>isSelected(context,event.conversationId)&&context.follow.next!==null},{actions:[assign({follow:({context})=>({...context.follow,joined:false})}),raise({resume:true,type:"READ_MESSAGES"})],guard:({context,event})=>isSelected(context,event.conversationId)&&context.follow.joined},{actions:({context})=>{resume(context)},guard:({context,event})=>isSelected(context,event.conversationId)&&(event.end==="cut"||event.end==="disconnected")},{actions:enqueueActions(({context,enqueue,event})=>{enqueue.assign({follow:noFollow});enqueue.raise({type:"RELOAD_QUEUE"});enqueue.raise({type:"RELOAD_CONVERSATIONS"});const wait=event.end==="ended"?shownWaitOf(context):null;if(wait!==null){enqueue.raise({...wait,type:"WATCH_WAIT"})}}),guard:({context,event})=>isSelected(context,event.conversationId)}],"chat.resume_empty":{actions:[assign({follow:noFollow}),raise({resume:false,type:"READ_MESSAGES"})],guard:({context,event})=>isSelected(context,event.conversationId)},"chat.run_status":{actions:assign({follow:({context,event})=>{const{runStatus}=event;const invocationId=invocationIdOf(runStatus.invocationId);return runStatus.kind==="next_turn"?{...context.follow,next:{invocationId,userMessage:userMessage(runStatus.userMessage.id,runStatus.userMessage.text)}}:{invocationId,joined:true,next:null}}}),guard:({context,event})=>isSelected(context,event.conversationId)},"chat.turn_named":{actions:assign({dropped:null}),guard:({context,event})=>isSelected(context,event.conversationId)}},states:{composer:{initial:"idle",on:{QUEUE:{actions:assign({failure:composerBusy})},SUBMIT:{actions:assign({failure:composerBusy})}},states:{cancelling:{invoke:{input:({context,event})=>({invocationId:namedTurnOf2(event)??runningTurnOf(context),runtime:context.runtime}),onDone:{actions:assign({follow:noFollow}),target:"idle"},onError:[{actions:assign(failedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{actions:assign(failedWith("later")),target:"idle"}],src:"cancelTurn"}},changingQueue:{invoke:{input:({context,event})=>({change:event.type==="UPDATE_QUEUED"||event.type==="REMOVE_QUEUED"?event:null,conversationId:context.conversationId,runtime:context.runtime}),onDone:{actions:raise({type:"RELOAD_QUEUE"}),target:"idle"},onError:[{actions:assign(failedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{actions:[assign(failedWith("later")),raise({type:"RELOAD_QUEUE"})],target:"idle"}],src:"changeQueued"}},creating:{invoke:{input:({context,event})=>({newChat:context.newChat,runtime:context.runtime,submit:submitOf(event)}),onDone:{actions:[assign({conversationId:({event})=>event.output.conversation.id,conversations:({context,event})=>[event.output.conversation,...context.conversations],draft:({context,event})=>event.output.uploadFailure===null?context.draft:draftBack(context),failure:({event})=>event.output.uploadFailure,follow:noFollow,newChat:{}}),({context,event})=>{context.host.sessions?.write(context.place,{conversationId:event.output.conversation.id,fromNewChat:true});if(event.output.uploadFailure===null){sendThroughChat(context,event.output.submit)}}],target:"idle"},onError:[{actions:assign(sendFailedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{actions:assign(sendFailedWith("later")),target:"idle"}],src:"createConversation"}},idle:{entry:assign({sending:""}),on:{QUEUE:[{actions:assign({failure:noOpenConversation}),guard:({context})=>context.conversationId===null},{actions:"takeDraft",target:"queueing"}],REMOVE_QUEUED:{target:"changingQueue"},STOP:[{guard:({context})=>runningTurnOf(context)===null&&isStreaming(context),target:"stopping"},{actions:stopChat,target:"cancelling"}],SUBMIT:[{guard:({context,event})=>isLaunch(event)&&context.conversationId===null,target:"creating"},{guard:({context,event})=>isMessageLaunch(event)&&turnRuns(context),target:"queueing"},{actions:assign({failure:launchIntoBusyConversation}),guard:({context,event})=>isLaunch(event)&&turnRuns(context)},{actions:[assign({dropped:null,failure:null,follow:noFollow}),({context,event})=>{sendThroughChat(context,submitOf(event))}],guard:({event})=>isLaunch(event)},{actions:"takeDraft",guard:({context})=>context.conversationId===null,target:"creating"},{actions:assign({failure:runningAnswerTakesNoFiles}),guard:({context,event})=>turnRuns(context)&&hasAttachments(event)},{actions:"takeDraft",guard:({context})=>turnRuns(context),target:"steering"},{actions:"takeDraft",guard:({event})=>(event.files?.length??0)>0,target:"uploading"},{actions:[assign({draft:"",dropped:null,failure:null,follow:noFollow}),({context,event})=>{sendThroughChat(context,submitOf(event))}]}],UPDATE_QUEUED:{target:"changingQueue"}}},queueing:{invoke:{input:({context,event})=>({conversationId:context.conversationId,launchId:event.type==="SUBMIT"?event.launchId:undefined,runtime:context.runtime,text:event.type==="QUEUE"||event.type==="SUBMIT"?event.text:""}),onDone:{actions:[assign({failure:null}),{params:({event})=>event.output,type:"followSent"}],target:"idle"},onError:[{actions:assign(sendFailedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{actions:assign(sendFailedWith("later")),target:"idle"}],src:"queueMessage"}},steering:{invoke:{input:({context,event})=>({conversationId:context.conversationId,invocationId:runningTurnOf(context),runtime:context.runtime,text:event.type==="SUBMIT"?event.text:""}),onDone:{actions:[assign({failure:null}),{params:({event})=>event.output,type:"followSent"}],target:"idle"},onError:[{actions:assign(sendFailedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{actions:assign(sendFailedWith("later")),target:"idle"}],src:"steer"}},stopping:{on:{"chat.failed":{guard:({context,event})=>isSelected(context,event.conversationId),target:"idle"},"chat.finished":{guard:({context,event})=>isSelected(context,event.conversationId),target:"idle"},"chat.run_status":{actions:stopChat,guard:({context,event})=>isSelected(context,event.conversationId)&&namedTurnOf2(event)!==null,target:"cancelling"},"chat.turn_named":{actions:stopChat,guard:({context,event})=>isSelected(context,event.conversationId),target:"cancelling"}}},uploading:{invoke:{input:({context,event})=>({conversationId:context.conversationId,runtime:context.runtime,submit:submitOf(event)}),onDone:{actions:[assign({failure:null,follow:noFollow}),({context,event})=>{sendThroughChat(context,event.output)}],target:"idle"},onError:[{actions:assign(sendFailedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{actions:assign(sendFailedWith("later")),target:"idle"}],src:"uploadFiles"}}}},conversations:{initial:"idle",on:{RELOAD_CONVERSATIONS:".loading"},states:{idle:{},loading:{invoke:{input:({context})=>({historyScope:context.historyScope,runtime:context.runtime,subject:context.subject}),onDone:{actions:assign({conversations:({event})=>event.output}),target:"idle"},onError:[{actions:assign(failedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{target:"idle"}],src:"listConversations"}}}},follow:{initial:"idle",on:{READ_MESSAGES:".reading"},states:{idle:{},reading:{invoke:{input:({context,event})=>({conversationId:context.conversationId,resume:event.type==="READ_MESSAGES"&&event.resume,runtime:context.runtime}),onDone:{actions:[assign(({context,event})=>afterRead(context,event.output)),({context,event})=>{showMessages(context,event.output);if(event.output.resume){resume(context)}}],target:"idle"},onError:[{actions:assign(failedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{actions:assign(failedWith("later")),target:"idle"}],src:"readMessages"}}}},queue:{initial:"check",on:{RELOAD_QUEUE:".check"},states:{check:{always:[{guard:({context})=>context.conversationId===null,target:"idle"},{target:"loading"}]},idle:{},loading:{invoke:{input:({context})=>({conversationId:context.conversationId,runtime:context.runtime}),onDone:{actions:assign({queuedMessages:({event})=>event.output}),target:"idle"},onError:[{actions:assign(failedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"#chatSession.blocked"},{target:"idle"}],src:"listQueued"}}}},wait:{initial:"idle",on:{WATCH_WAIT:{reenter:true,target:".watching"},"chat.turn_named":{guard:({context,event})=>isSelected(context,event.conversationId),target:".idle"}},states:{idle:{},watching:{invoke:{input:({context,event})=>({conversationId:event.type==="WATCH_WAIT"?event.conversationId:null,invocationId:event.type==="WATCH_WAIT"?event.invocationId:null,runtime:context.runtime}),onDone:{actions:({context})=>{if(shownWaitOf(context)!==null){resume(context)}},target:"idle"},onError:{target:"idle"},src:"watchWait"}}}}},type:"parallel"},starting:{invoke:{input:({context})=>({historyScope:context.historyScope,placeContext:context.placeContext,runtime:context.runtime,subject:context.subject,trail:context.host.trail}),onDone:[{actions:assign({conversations:({event})=>event.output.conversations,placeContext:({event})=>event.output.placeContext}),guard:({context,event})=>event.output.conversations.some(({id})=>id===context.conversationId),target:"switching"},{actions:assign({conversationId:({event})=>event.output.conversations[0]?.id??null,conversations:({event})=>event.output.conversations,placeContext:({event})=>event.output.placeContext}),guard:({context,event})=>context.subject!==undefined&&event.output.conversations.length>0,target:"switching"},{actions:assign({conversationId:null,conversations:({event})=>event.output.conversations,placeContext:({event})=>event.output.placeContext}),target:"ready"}],onError:[{actions:assign(failedWith("first")),guard:({event})=>blocks(event.error,"first"),target:"blocked"},{actions:assign(failedWith("first")),target:"ready"}],src:"loadSession"}},switching:{invoke:{input:({context})=>({conversationId:context.conversationId,resume:false,runtime:context.runtime}),onDone:{actions:[({context,event})=>{showMessages(context,event.output);if(event.output.openTurn!==null&&!isStreaming(context)){resume(context)}},assign({follow:({event})=>({...noFollow,invocationId:event.output.openTurn?.invocationId??null})})],target:"ready"},onError:[{actions:assign(failedWith("later")),guard:({event})=>blocks(event.error,"later"),target:"blocked"},{actions:assign(failedWith("later")),target:"ready"}],src:"readMessages"},on:{NEW_CHAT:{actions:raise(({event})=>event),target:"ready"},SELECT_CONVERSATION:{actions:raise(({event})=>event),target:"ready"}}}}});import{jsx as jsx2,jsxs}from"react/jsx-runtime";var SessionActor=createContext2(null);var useSessionActor=()=>{const actor=useContext2(SessionActor);if(actor===null){throw new Error("The chat hooks need a ChatSessionProvider.")}return actor};var statusOf=(snapshot)=>{if(snapshot.matches("blocked")){return"blocked"}if(snapshot.matches("ready")){return"ready"}return snapshot.matches("switching")?"switching":"starting"};var busyOf=(snapshot)=>snapshot.matches("ready")&&!snapshot.matches({ready:{composer:"idle"}});var useChatStatus=(actor)=>{const chat=useSelector(actor,({context})=>context.registry.chat(context.conversationId));return useSyncExternalStore2(chat["~registerStatusCallback"],()=>chat.status,()=>chat.status)};var useChatSession2=()=>{const actor=useSessionActor();const status=useSelector(actor,statusOf);const busy=useSelector(actor,busyOf);const context=useSelector(actor,(snapshot)=>snapshot.context);const chatStatus=useChatStatus(actor);const call=useCallback((operation)=>actor.getSnapshot().context.runtime.runPromise(Effect3.match(callChatSurface(operation),{onFailure:({error})=>({error,ok:false}),onSuccess:(value)=>({ok:true,value})})),[actor]);const actions=useMemo2(()=>({newChat:(options={})=>{actor.send({...options,type:"NEW_CHAT"})},queue:(text)=>{actor.send({text,type:"QUEUE"})},readMessages:()=>{actor.send({resume:false,type:"READ_MESSAGES"})},reloadConversations:()=>{actor.send({type:"RELOAD_CONVERSATIONS"})},removeQueuedMessage:(queuedMessageId,revision)=>{actor.send({queuedMessageId,revision,type:"REMOVE_QUEUED"})},retry:()=>{actor.send({type:"RETRY"})},selectConversation:(conversationId)=>{actor.send({conversationId,type:"SELECT_CONVERSATION"})},setCapabilities:(capabilities)=>{actor.send({capabilities,type:"SET_CAPABILITIES"})},setDraft:(text)=>{actor.send({text,type:"DRAFT"})},stop:()=>{actor.send({type:"STOP"})},submit:(submit)=>{actor.send({...submit,type:"SUBMIT"})},updateQueuedMessage:(queuedMessageId,content,revision)=>{actor.send({content,queuedMessageId,revision,type:"UPDATE_QUEUED"})}}),[actor]);const controls=useMemo2(()=>chatControls(context.host),[context.host]);return{...actions,blocked:context.blocked,busy,call,capabilities:context.capabilities,controls,conversationId:context.conversationId,conversations:context.conversations,draft:context.draft,failure:context.failure,place:context.place,placeContext:context.placeContext,queuedMessages:context.queuedMessages,sendMode:chatStatus==="submitted"||chatStatus==="streaming"||context.follow.invocationId!==null?"running":"idle",status}};var useCiChat2=()=>{const actor=useSessionActor();const chat=useSelector(actor,({context})=>context.registry.chat(context.conversationId));return useChat({chat})};var IntentCardWatch=()=>{const registry=useContext2(IntentsContext)?.registry;const{readMessages,status}=useChatSession2();const{messages,status:answer}=useCiChat2();const[tracker]=useState2(createIntentCardEndTracker);useEffect2(()=>{for(const notice of tracker.observe(status,messages)){registry?.publish(notice)}},[messages,registry,status,tracker]);const waiting=status==="ready"&&answer!=="streaming"&&answer!=="submitted"&&intentCardPending(messages);useEffect2(()=>{if(!waiting){return}const timer=setInterval(readMessages,intentCardReloadMs);return()=>{clearInterval(timer)}},[readMessages,waiting]);return null};var ChatSessionProvider2=({api,children,historyScope,host,place,subject,transport})=>{const input={api,...historyScope!==undefined&&{historyScope},...host!==undefined&&{host},place,...subject!==undefined&&{subject},transport};const actor=useActorRef(chatSessionMachine,{input});return jsxs(SessionActor.Provider,{value:actor,children:[children,jsx2(IntentCardWatch,{})]})};import{useMutation,useQueryClient}from"@tanstack/react-query";import{useCallback as useCallback2,useEffect as useEffect3,useRef as useRef2,useState as useState3,useSyncExternalStore as useSyncExternalStore3}from"react";import{queryOptions,skipToken}from"@tanstack/react-query";var intentKeys={list:(cacheScope)=>["ai","intents",cacheScope,"list"]};var callIntents=async(api,op,input,signal)=>{const answer=async()=>{try{return await api.call(op,input,signal===undefined?{}:{signal})}catch(error){throw new AiFailureError2({code:"unavailable",message:"The Intents API failed",retryable:true},{cause:error})}};const result=await answer();if(!result.ok){throw new AiFailureError2(result.error)}return result.value};var retryRetryable=(failureCount,error)=>error.error.retryable&&failureCount<3;var intentListQuery=(cacheScope,api)=>queryOptions({queryFn:api===undefined?skipToken:({signal})=>callIntents(api,"list",{},signal),queryKey:intentKeys.list(cacheScope),retry:retryRetryable});var storedTarget=(options)=>options.resultTarget==="notification"&&options.returnPage!==undefined?{resultTarget:"notification",returnPage:options.returnPage}:{resultTarget:options.resultTarget};var outcomeStates={completed:"done",failed:"failed",needs_input:"needs_input",not_allowed:"failed",started:"done"};var stateOf=(mutation)=>{if(mutation.status==="idle"){return"ready"}if(mutation.status==="pending"){return"working"}return mutation.status==="error"?"failed":outcomeStates[mutation.data.outcome.kind]};var noIntents=new AiFailureError2({code:"unavailable",message:"No IntentsApi is set on IntentsProvider",retryable:false});var useIntentDispatch2=(fqn,options)=>{const intentsScope=useIntentsScope2();const{registry}=intentsScope;const queryClient=useQueryClient();const latest=useRef2(undefined);const listedEntry=async(api,cacheScope)=>{const entries=await queryClient.ensureQueryData(intentListQuery(cacheScope,api)).catch(()=>[]);return entries.find((listed)=>listed.fqn===fqn)};const settle=async(api,{cacheScope,registry:dispatchRegistry},outcome,idempotencyKey,signal)=>{const notify=options.resultTarget==="notification";if(outcome.kind==="completed"||outcome.kind==="failed"){dispatchRegistry.publish({fqn,handle:undefined,outcome});if(notify){const entry=await listedEntry(api,cacheScope);dispatchRegistry.show({displayName:entry?.displayName??fqn,fqn,id:idempotencyKey,outcome})}return{handle:undefined,outcome}}if(outcome.kind!=="started"){return{handle:undefined,outcome}}const{handle}=outcome;const entry=await listedEntry(api,cacheScope);if(notify){dispatchRegistry.keep({displayName:entry?.displayName??fqn,fqn,handle})}if(entry?.resultMode!=="sync"||signal.aborted){return{handle,outcome}}const end=await callIntents(api,"wait",{handle},signal);if(!notify){dispatchRegistry.publish({fqn,handle,outcome:end})}return{handle,outcome:end}};const mutation=useMutation({mutationFn:async({idempotencyKey,inputs,scope,signal})=>{const intents=scope.api;if(intents===undefined){throw noIntents}const outcome=await callIntents(intents,"dispatch",{fqn,idempotencyKey,inputs,...storedTarget(options)});return await settle(intents,scope,outcome,idempotencyKey,signal)}});const{mutateAsync}=mutation;const[runEnds,setRunEnds]=useState3(()=>new Map);useIntentResult2(fqn,(notice)=>{const{handle}=notice;if(handle!==undefined){setRunEnds((ends)=>new Map(ends).set(handle,notice))}});const returnedEnd=useCallback2(()=>registry.adopted(fqn),[fqn,registry]);const returned=useSyncExternalStore3(registry.subscribe,returnedEnd,returnedEnd);useEffect3(()=>()=>{latest.current?.abort()},[]);const dispatch=useCallback2(async(inputs,call={})=>{latest.current?.abort();const controller=new AbortController;latest.current=controller;try{const{outcome}=await mutateAsync({idempotencyKey:call.idempotencyKey??crypto.randomUUID(),inputs,scope:intentsScope,signal:controller.signal});return{ok:true,value:outcome}}catch(error){return{error:error instanceof AiFailureError2?error.error:{code:"internal",message:String(error),retryable:false},ok:false}}},[intentsScope,mutateAsync]);if(mutation.status==="idle"&&returned!==undefined){return{dispatch,error:undefined,handle:returned.handle,outcome:returned.outcome,state:outcomeStates[returned.outcome.kind]}}const settled=mutation.data;const runEnd=settled?.outcome.kind==="started"&&settled.handle!==undefined?runEnds.get(settled.handle):undefined;if(settled!==undefined&&runEnd!==undefined){return{dispatch,error:undefined,handle:settled.handle,outcome:runEnd.outcome,state:outcomeStates[runEnd.outcome.kind]}}return{dispatch,error:mutation.error?.error,handle:mutation.data?.handle,outcome:mutation.data?.outcome,state:stateOf(mutation)}};import{useQuery}from"@tanstack/react-query";var useIntents2=()=>{const{api,cacheScope}=useIntentsScope2();const list=useQuery(intentListQuery(cacheScope,api));return{enabled:api!==undefined,list}};import{useCallback as useCallback3,useSyncExternalStore as useSyncExternalStore4}from"react";var useLaunch2=()=>{const{registry,scope}=useIntentsScope2();return useCallback3((turn,{target,...how}={})=>{const receive=registry.launchTarget(scope,target)?.receive;if(receive===undefined){return}const launch={...how,launchId:crypto.randomUUID(),turn};receive(launch);return launch.launchId},[registry,scope])};var useHasLaunchTarget2=(target)=>{const{registry,scope}=useIntentsScope2();const snapshot=useCallback3(()=>registry.launchTarget(scope,target)!==undefined,[registry,scope,target]);return useSyncExternalStore4(registry.subscribe,snapshot,snapshot)};import{useEffect as useEffect4,useRef as useRef3}from"react";import*as Schema5 from"effect/Schema";var isAgentId=Schema5.is(AgentId2);var submitChatLaunch2=(chat,{agentId,conversation,launchId,prefill,trail,turn})=>{const text=turn.kind==="intent"?turn.fqn:turn.text;const current=conversation==="current"&&chat.conversationId!==null;const named=isAgentId(agentId)?agentId:chat.pinnedAgentId;const agent=turn.kind==="intent"?undefined:named;const needsAgent=turn.kind!=="intent"&&!current&&agent===undefined&&chat.plainChat===false;if(prefill===true||needsAgent){chat.setDraft(turn.kind==="intent"?"":text);return}if(!current){chat.newChat(agent===undefined?{}:{agentId:agent})}const launched={launchId,text,...trail!==undefined&&trail.length>0&&{trail}};switch(turn.kind){case"intent":{chat.submit({...launched,launch:{fqn:turn.fqn,inputs:turn.inputs}});return}case"skill":{chat.submit({...launched,capabilities:[{id:turn.skillId,kind:"skill"}]});return}default:{chat.submit(launched)}}};var useChatLaunchTarget2=({id,onLaunch,preferred,session})=>{const ready=session.status==="ready";const held=useRef3(undefined);useEffect4(()=>{const launch=held.current;if(ready&&launch!==undefined){held.current=undefined;submitChatLaunch2(session,launch)}},[ready,session]);const takes=ready||preferred===true&&session.status==="starting";useRegisterOptionalPiece({id,kind:"chat",preferred,receive:takes?(launch)=>{onLaunch?.();if(ready){submitChatLaunch2(session,launch)}else{held.current=launch}}:undefined})};import{createContext as createContext3,useCallback as useCallback4,useContext as useContext3,useEffect as useEffect5,useId,useSyncExternalStore as useSyncExternalStore5}from"react";var jsonLdBlocks='script[type="application/ld+json"]';var readerSource="json-ld";var isRecord=(value)=>hasObjectRuntimeKind2(value)&&value!==null&&!Array.isArray(value);var isTypedNode=(value)=>isRecord(value)&&hasStringRuntimeKind2(value["@type"]);var nodesOf=(text)=>{let parsed;try{parsed=asRuntimeValue2(JSON.parse(text))}catch{return[]}if(Array.isArray(parsed)){return parsed}const graph=isRecord(parsed)?parsed["@graph"]:undefined;return Array.isArray(graph)?graph:[parsed]};var isBlock=(node)=>node instanceof Element&&node.matches(jsonLdBlocks);var holdsBlock=(node)=>node instanceof Element&&(node.matches(jsonLdBlocks)||node.querySelector(jsonLdBlocks)!==null);var touchesBlocks=({addedNodes,removedNodes,target})=>isBlock(target)||isBlock(target.parentNode)||[...addedNodes,...removedNodes].some(holdsBlock);var readPageJsonLd=(trail)=>{const blockNumbers=new WeakMap;let blocks=0;let sources=new Set;const read=()=>{const next=new Set;for(const block of document.querySelectorAll(jsonLdBlocks)){const number=blockNumbers.get(block)??(blocks+=1);blockNumbers.set(block,number);const nodes=nodesOf(block.textContent).filter(isTypedNode);for(const[at,data]of nodes.entries()){const source=`${readerSource}:${number}:${at}`;next.add(source);trail.setMetadata(source,data)}}for(const source of sources){if(!next.has(source)){trail.clearMetadata(source)}}sources=next};read();const observer=new MutationObserver((records)=>{if(records.some(touchesBlocks)){read()}});observer.observe(document,{characterData:true,childList:true,subtree:true});return()=>{observer.disconnect();for(const source of sources){trail.clearMetadata(source)}}};import{jsx as jsx3}from"react/jsx-runtime";var TrailContext=createContext3(undefined);var ContextTrailProvider2=({children,trail})=>jsx3(TrailContext.Provider,{value:trail,children});var useTrailBuffer2=()=>useContext3(TrailContext);var noEntries=[];var unsubscribeNothing=()=>{return};var noSubscription=()=>unsubscribeNothing;var useTrailEntries2=(trail)=>{const entries=trail?.entries??(()=>noEntries);return useSyncExternalStore5(trail?.subscribe??noSubscription,entries,entries)};var useContextTrailEntries2=()=>useTrailEntries2(useContext3(TrailContext));var useRecording=(trail)=>useSyncExternalStore5(trail?.subscribe??noSubscription,()=>trail?.recording()??false,()=>false);var useRecordPageVisit2=({app,page,title})=>{const trail=useContext3(TrailContext);const recording=useRecording(trail);useEffect5(()=>{if(recording){trail?.recordPageVisit({app,page,title})}},[app,page,recording,title,trail])};var useTrailMetadata2=(data,source)=>{const trail=useContext3(TrailContext);const own=useId();const id=source??own;const recording=useRecording(trail);useRegisterOptionalPiece({id,kind:"trail_source"});useEffect5(()=>()=>{trail?.clearMetadata(id)},[id,trail]);useEffect5(()=>{if(recording){trail?.setMetadata(id,data)}},[data,id,recording,trail])};var useTrailEvent2=(source)=>{const trail=useContext3(TrailContext);const own=useId();const id=source??own;return useCallback4((push)=>{trail?.pushEvent(id,push)},[id,trail])};var usePageJsonLd2=()=>{const trail=useContext3(TrailContext);const recording=useRecording(trail);useRegisterOptionalPiece({id:readerSource,kind:"trail_source"});useEffect5(()=>{if(!recording||trail===undefined){return}return readPageJsonLd(trail)},[recording,trail])};export{useIntentsScope2,useOptionalIntentsScope2,IntentsProvider2,IntentsRegistryScope2,useRegisterPiece2,usePieces2,useIntentResult2,chatBlockedKinds2,chatSurfaceLayer,makeChatSessionRuntime,toSessionFailure,callChatSurface,retryRead,chatFeatureFlags2,createBrowserFilePort2,openRunStates2,isOpenRunState2,trailBufferSize2,createTrailBuffer2,turnTrail2,useChatSession2,useCiChat2,ChatSessionProvider2,useIntentDispatch2,useIntents2,useLaunch2,useHasLaunchTarget2,submitChatLaunch2,useChatLaunchTarget2,ContextTrailProvider2,useTrailBuffer2,useTrailEntries2,useContextTrailEntries2,useRecordPageVisit2,useTrailMetadata2,useTrailEvent2,usePageJsonLd2};
|
|
File without changes
|