@ai-matrx/agents 0.10.6 → 0.11.0

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/content-transfer/index.cjs +1422 -0
  3. package/dist/content-transfer/index.cjs.map +1 -0
  4. package/dist/content-transfer/index.d.cts +84 -0
  5. package/dist/content-transfer/index.d.ts +84 -0
  6. package/dist/content-transfer/index.js +1404 -0
  7. package/dist/content-transfer/index.js.map +1 -0
  8. package/dist/content-transfer/react/index.cjs +1564 -0
  9. package/dist/content-transfer/react/index.cjs.map +1 -0
  10. package/dist/content-transfer/react/index.d.cts +63 -0
  11. package/dist/content-transfer/react/index.d.ts +63 -0
  12. package/dist/content-transfer/react/index.js +1539 -0
  13. package/dist/content-transfer/react/index.js.map +1 -0
  14. package/dist/index.cjs +23 -0
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +2 -1
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.js +23 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/mandates/index.cjs +8 -2
  21. package/dist/mandates/index.cjs.map +1 -1
  22. package/dist/mandates/index.d.cts +11 -5
  23. package/dist/mandates/index.d.ts +11 -5
  24. package/dist/mandates/index.js +8 -2
  25. package/dist/mandates/index.js.map +1 -1
  26. package/dist/matrx/index.cjs +23 -0
  27. package/dist/matrx/index.cjs.map +1 -1
  28. package/dist/matrx/index.d.cts +13 -646
  29. package/dist/matrx/index.d.ts +13 -646
  30. package/dist/matrx/index.js +23 -0
  31. package/dist/matrx/index.js.map +1 -1
  32. package/dist/operations--f5ko9Su.d.cts +659 -0
  33. package/dist/operations-BT5kKMHl.d.cts +203 -0
  34. package/dist/operations-BT5kKMHl.d.ts +203 -0
  35. package/dist/operations-Dp4ut-ac.d.ts +659 -0
  36. package/dist/react/index.cjs.map +1 -1
  37. package/dist/react/index.d.cts +44 -244
  38. package/dist/react/index.d.ts +44 -244
  39. package/dist/react/index.js.map +1 -1
  40. package/mandates/snapshots/keys.0.10.6.json +2 -1
  41. package/mandates/snapshots/keys.0.10.7.json +470 -0
  42. package/mandates/snapshots/keys.0.11.0.json +475 -0
  43. package/package.json +24 -3
@@ -0,0 +1,1564 @@
1
+ "use client";
2
+ "use strict";
3
+ "use client";
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
+
32
+ // content-transfer/react/index.tsx
33
+ var react_exports = {};
34
+ __export(react_exports, {
35
+ MatrxContentTransferProvider: () => MatrxContentTransferProvider
36
+ });
37
+ module.exports = __toCommonJS(react_exports);
38
+ var React = __toESM(require("react"), 1);
39
+ var import_content_transfer2 = require("@ai-matrx/design-system/content-transfer");
40
+
41
+ // content-transfer/index.ts
42
+ var import_content_transfer = require("@ai-matrx/kit/content-transfer");
43
+
44
+ // mandates/keys.generated.ts
45
+ var MANDATE_KEYS = {
46
+ agent_apps__auto_create: "agent_apps.auto_create",
47
+ agent_apps__auto_create_lightning: "agent_apps.auto_create_lightning",
48
+ agent_apps__metadata: "agent_apps.metadata",
49
+ agent_apps__prompt_app_dev: "agent_apps.prompt_app_dev",
50
+ agent_factory__structure_builder: "agent_factory.structure_builder",
51
+ alchemy__prepare_content: "alchemy.prepare_content",
52
+ ambient__page_guidance: "ambient.page_guidance",
53
+ ambient__spoken_summary: "ambient.spoken_summary",
54
+ chat__cx_default: "chat.cx_default",
55
+ chat__default_new_chat: "chat.default_new_chat",
56
+ chat__quick_audio_plan: "chat.quick_audio_plan",
57
+ chat__quick_fair_news: "chat.quick_fair_news",
58
+ chat__quick_flashcards: "chat.quick_flashcards",
59
+ chat__quick_image: "chat.quick_image",
60
+ chat__quick_org_chart: "chat.quick_org_chart",
61
+ chat__quick_research: "chat.quick_research",
62
+ chat__quick_showcase: "chat.quick_showcase",
63
+ chat__quick_writing_partner: "chat.quick_writing_partner",
64
+ chat__response_mode_brainstorm: "chat.response_mode_brainstorm",
65
+ chat__response_mode_data: "chat.response_mode_data",
66
+ chat__response_mode_research: "chat.response_mode_research",
67
+ chat__response_mode_video: "chat.response_mode_video",
68
+ code_editor__code_edit: "code_editor.code_edit",
69
+ code_editor__dynamic_context_edit: "code_editor.dynamic_context_edit",
70
+ code_editor__prompt_app_ui_edit: "code_editor.prompt_app_ui_edit",
71
+ coding_session__managed_translation_reference: "coding_session.managed_translation_reference",
72
+ commerce_intake__assess_value: "commerce_intake.assess_value",
73
+ commerce_intake__extract_vision: "commerce_intake.extract_vision",
74
+ commerce_intake__grading: "commerce_intake.grading",
75
+ commerce_intake__instant_analysis: "commerce_intake.instant_analysis",
76
+ commerce_intake__refute_no_value: "commerce_intake.refute_no_value",
77
+ commerce_intake__research_product: "commerce_intake.research_product",
78
+ commerce_intake__segment_photos: "commerce_intake.segment_photos",
79
+ commerce_intake__verify_enrichment: "commerce_intake.verify_enrichment",
80
+ content_ir__component_artisan: "content_ir.component_artisan",
81
+ content_ir__kind_architect: "content_ir.kind_architect",
82
+ content_ir__kind_component_builder: "content_ir.kind_component_builder",
83
+ content_ir__kind_creator: "content_ir.kind_creator",
84
+ content_plan__brief_writer: "content_plan.brief_writer",
85
+ content_plan__entity_attacher: "content_plan.entity_attacher",
86
+ content_plan__entity_curator: "content_plan.entity_curator",
87
+ content_plan__family_namer: "content_plan.family_namer",
88
+ content_plan__keyword_strategist: "content_plan.keyword_strategist",
89
+ content_plan__p3_family: "content_plan.p3_family",
90
+ content_plan__p4_write: "content_plan.p4_write",
91
+ content_plan__p5_review: "content_plan.p5_review",
92
+ content_plan__p6_build: "content_plan.p6_build",
93
+ content_plan__p6_build__about: "content_plan.p6_build.about",
94
+ content_plan__p6_build__blog: "content_plan.p6_build.blog",
95
+ content_plan__p6_build__comparison: "content_plan.p6_build.comparison",
96
+ content_plan__p6_build__contact: "content_plan.p6_build.contact",
97
+ content_plan__p6_build__faq: "content_plan.p6_build.faq",
98
+ content_plan__p6_build__guide: "content_plan.p6_build.guide",
99
+ content_plan__p6_build__home: "content_plan.p6_build.home",
100
+ content_plan__p6_build__index: "content_plan.p6_build.index",
101
+ content_plan__p6_build__location: "content_plan.p6_build.location",
102
+ content_plan__p6_build__pillar: "content_plan.p6_build.pillar",
103
+ content_plan__p6_build__pricing: "content_plan.p6_build.pricing",
104
+ content_plan__p6_build__service: "content_plan.p6_build.service",
105
+ content_plan__plan_reviewer: "content_plan.plan_reviewer",
106
+ content_plan__route_picker: "content_plan.route_picker",
107
+ content_plan__shape_planner: "content_plan.shape_planner",
108
+ conversation__action_auditor: "conversation.action_auditor",
109
+ conversation__decision_ledger: "conversation.decision_ledger",
110
+ conversation__drift_auditor: "conversation.drift_auditor",
111
+ conversation__outcome_summarizer: "conversation.outcome_summarizer",
112
+ conversation__vision_extractor: "conversation.vision_extractor",
113
+ conversation__vision_interviewer: "conversation.vision_interviewer",
114
+ crm__journalist_beat_analyst: "crm.journalist_beat_analyst",
115
+ crm__media_list_ranker: "crm.media_list_ranker",
116
+ crm__outreach_draft_reviewer: "crm.outreach_draft_reviewer",
117
+ crm__outreach_personalization_coach: "crm.outreach_personalization_coach",
118
+ crm__outreach_personalization_writer: "crm.outreach_personalization_writer",
119
+ crm__outreach_pitch_writer: "crm.outreach_pitch_writer",
120
+ crm__outreach_recipient_shortlister: "crm.outreach_recipient_shortlister",
121
+ crm__outreach_reply_drafter: "crm.outreach_reply_drafter",
122
+ crm__party_kind_judge: "crm.party_kind_judge",
123
+ crm__save_contact: "crm.save_contact",
124
+ data__page_guidance: "data.page_guidance",
125
+ dictionary__workspace_guide: "dictionary.workspace_guide",
126
+ education__admin_guidance: "education.admin_guidance",
127
+ education__analytics_narrate: "education.analytics_narrate",
128
+ education__audio_study_guidance: "education.audio_study_guidance",
129
+ education__card_image_generator: "education.card_image_generator",
130
+ education__card_image_prompt_writer: "education.card_image_prompt_writer",
131
+ education__card_image_qc_judge: "education.card_image_qc_judge",
132
+ education__card_image_web_source: "education.card_image_web_source",
133
+ education__classes_guidance: "education.classes_guidance",
134
+ education__creator_guidance: "education.creator_guidance",
135
+ education__data_guidance: "education.data_guidance",
136
+ education__exam_prep_guidance: "education.exam_prep_guidance",
137
+ education__family_guidance: "education.family_guidance",
138
+ education__fastfire_guidance: "education.fastfire_guidance",
139
+ education__features_guidance: "education.features_guidance",
140
+ education__flashcards_guidance: "education.flashcards_guidance",
141
+ education__game_guidance: "education.game_guidance",
142
+ education__grade_handwritten: "education.grade_handwritten",
143
+ education__grade_work_guidance: "education.grade_work_guidance",
144
+ education__kit_title: "education.kit_title",
145
+ education__learn_guidance: "education.learn_guidance",
146
+ education__levels_guidance: "education.levels_guidance",
147
+ education__library_guidance: "education.library_guidance",
148
+ education__media_guidance: "education.media_guidance",
149
+ education__memory_generate: "education.memory_generate",
150
+ education__memory_guidance: "education.memory_guidance",
151
+ education__memory_hint: "education.memory_hint",
152
+ education__mind_maps_guidance: "education.mind_maps_guidance",
153
+ education__mindmap_generate: "education.mindmap_generate",
154
+ education__notes_generate: "education.notes_generate",
155
+ education__notes_guidance: "education.notes_guidance",
156
+ education__offline_guidance: "education.offline_guidance",
157
+ education__page_guidance: "education.page_guidance",
158
+ education__plan_generate: "education.plan_generate",
159
+ education__planner_guidance: "education.planner_guidance",
160
+ education__practice_oral_guidance: "education.practice_oral_guidance",
161
+ education__practice_tests_guidance: "education.practice_tests_guidance",
162
+ education__progress_guidance: "education.progress_guidance",
163
+ education__quiz_deepen_item: "education.quiz_deepen_item",
164
+ education__quiz_generate: "education.quiz_generate",
165
+ education__quiz_generate_from_source: "education.quiz_generate_from_source",
166
+ education__quizzes_guidance: "education.quizzes_guidance",
167
+ education__spoken_practice_design: "education.spoken_practice_design",
168
+ education__spoken_practice_design_language: "education.spoken_practice_design_language",
169
+ education__spoken_practice_grade: "education.spoken_practice_grade",
170
+ education__spoken_practice_grade_pronunciation: "education.spoken_practice_grade_pronunciation",
171
+ education__spoken_practice_review: "education.spoken_practice_review",
172
+ education__start_guidance: "education.start_guidance",
173
+ education__study_aids_guidance: "education.study_aids_guidance",
174
+ education__study_pack_flashcards: "education.study_pack_flashcards",
175
+ education__study_pack_lessons: "education.study_pack_lessons",
176
+ education__study_pack_notes: "education.study_pack_notes",
177
+ education__study_pack_quiz: "education.study_pack_quiz",
178
+ education__study_pack_v2_flashcards: "education.study_pack_v2_flashcards",
179
+ education__study_pack_v2_lessons: "education.study_pack_v2_lessons",
180
+ education__study_pack_v2_notes: "education.study_pack_v2_notes",
181
+ education__study_pack_v2_quiz: "education.study_pack_v2_quiz",
182
+ education__subjects_guidance: "education.subjects_guidance",
183
+ education__summaries_guidance: "education.summaries_guidance",
184
+ education__summarize: "education.summarize",
185
+ education__tutor_guidance: "education.tutor_guidance",
186
+ education__tutor_message: "education.tutor_message",
187
+ education__voice_tutor: "education.voice_tutor",
188
+ extend__browser_chat: "extend.browser_chat",
189
+ extend__pattern_from_data: "extend.pattern_from_data",
190
+ extend__structured_extractor: "extend.structured_extractor",
191
+ flashcards__enrich_card: "flashcards.enrich_card",
192
+ flashcards__expand_card: "flashcards.expand_card",
193
+ flashcards__generate_cards: "flashcards.generate_cards",
194
+ flashcards__generate_from_source: "flashcards.generate_from_source",
195
+ flashcards__grade_spoken: "flashcards.grade_spoken",
196
+ flashcards__grade_typed_answer: "flashcards.grade_typed_answer",
197
+ flashcards__help_live: "flashcards.help_live",
198
+ flashcards__helper_tts: "flashcards.helper_tts",
199
+ flashcards__make_quiz_items: "flashcards.make_quiz_items",
200
+ flashcards__micro_coach: "flashcards.micro_coach",
201
+ flashcards__review_batch: "flashcards.review_batch",
202
+ flashcards__spoken_front_tts: "flashcards.spoken_front_tts",
203
+ flashcards__verify_against_source: "flashcards.verify_against_source",
204
+ foundry__planner: "foundry.planner",
205
+ growth_loop__quality_analyze: "growth_loop.quality_analyze",
206
+ growth_loop__quality_brief: "growth_loop.quality_brief",
207
+ growth_loop__quality_crawl: "growth_loop.quality_crawl",
208
+ growth_loop__quality_fill: "growth_loop.quality_fill",
209
+ growth_loop__quality_measure: "growth_loop.quality_measure",
210
+ growth_loop__quality_plan: "growth_loop.quality_plan",
211
+ growth_loop__quality_publish: "growth_loop.quality_publish",
212
+ growth_loop__quality_realize: "growth_loop.quality_realize",
213
+ growth_loop__quality_research: "growth_loop.quality_research",
214
+ growth_loop__quality_serve: "growth_loop.quality_serve",
215
+ growth_loop__quality_suggest: "growth_loop.quality_suggest",
216
+ growth_loop__quality_writeback: "growth_loop.quality_writeback",
217
+ growth_loop__supervisor: "growth_loop.supervisor",
218
+ hindsight__crystallizer: "hindsight.crystallizer",
219
+ hindsight__replay_judge: "hindsight.replay_judge",
220
+ hindsight__reviewer: "hindsight.reviewer",
221
+ human_decisions__fallback_decider: "human_decisions.fallback_decider",
222
+ iteration__architect: "iteration.architect",
223
+ iteration__diagnostic: "iteration.diagnostic",
224
+ iteration__root_cause: "iteration.root_cause",
225
+ iteration__thinking_display: "iteration.thinking_display",
226
+ kg__cluster_namer: "kg.cluster_namer",
227
+ kg__ner_extractor: "kg.ner_extractor",
228
+ knowledge__document_verifier: "knowledge.document_verifier",
229
+ knowledge__qa_generator: "knowledge.qa_generator",
230
+ knowledge__section_summarizer: "knowledge.section_summarizer",
231
+ local__cloud_chat: "local.cloud_chat",
232
+ marketing__endowment_analysis: "marketing.endowment_analysis",
233
+ marketing__endowment_portfolio: "marketing.endowment_portfolio",
234
+ marketing__image_prompt: "marketing.image_prompt",
235
+ marketing__page_image: "marketing.page_image",
236
+ marketing__page_image_all_in_one: "marketing.page_image_all_in_one",
237
+ marketing__video_metadata: "marketing.video_metadata",
238
+ masterwork__approach_selector: "masterwork.approach_selector",
239
+ masterwork__audition_judge: "masterwork.audition_judge",
240
+ masterwork__bad_draft: "masterwork.bad_draft",
241
+ masterwork__checkup_auditor: "masterwork.checkup_auditor",
242
+ masterwork__coherence_partner: "masterwork.coherence_partner",
243
+ masterwork__conductor: "masterwork.conductor",
244
+ masterwork__corpus_cleaner: "masterwork.corpus_cleaner",
245
+ masterwork__corpus_synthesizer: "masterwork.corpus_synthesizer",
246
+ masterwork__draft_triage: "masterwork.draft_triage",
247
+ masterwork__exception_hunter: "masterwork.exception_hunter",
248
+ masterwork__exemplar_distiller: "masterwork.exemplar_distiller",
249
+ masterwork__intake_designer: "masterwork.intake_designer",
250
+ masterwork__monologue_distiller: "masterwork.monologue_distiller",
251
+ masterwork__outcome_judge: "masterwork.outcome_judge",
252
+ masterwork__relationship_auditor: "masterwork.relationship_auditor",
253
+ masterwork__rule_improver: "masterwork.rule_improver",
254
+ masterwork__rulebook_auditor: "masterwork.rulebook_auditor",
255
+ masterwork__scout: "masterwork.scout",
256
+ masterwork__source_distiller: "masterwork.source_distiller",
257
+ masterwork__template__chief_edit: "masterwork.template.chief_edit",
258
+ masterwork__template__chief_generate: "masterwork.template.chief_generate",
259
+ masterwork__template__editor: "masterwork.template.editor",
260
+ masterwork__template__maker: "masterwork.template.maker",
261
+ masterwork__timeline_distiller: "masterwork.timeline_distiller",
262
+ masterwork__timeline_segmenter: "masterwork.timeline_segmenter",
263
+ masterwork__transcript_distiller: "masterwork.transcript_distiller",
264
+ masterwork__transcript_shortlister: "masterwork.transcript_shortlister",
265
+ masterwork__understudy: "masterwork.understudy",
266
+ media__youtube_analyzer: "media.youtube_analyzer",
267
+ meet__live_intelligence: "meet.live_intelligence",
268
+ meet__live_notes: "meet.live_notes",
269
+ meet__wrap_up: "meet.wrap_up",
270
+ messaging__action_item_extraction: "messaging.action_item_extraction",
271
+ messaging__conversation_catch_up: "messaging.conversation_catch_up",
272
+ messaging__conversation_summary: "messaging.conversation_summary",
273
+ messaging__reply_drafting: "messaging.reply_drafting",
274
+ ner__deep_chunk_extractor: "ner.deep_chunk_extractor",
275
+ ner__document_orienter: "ner.document_orienter",
276
+ ner__entity_canonicalizer: "ner.entity_canonicalizer",
277
+ ner__finisher: "ner.finisher",
278
+ ner__item_proposer: "ner.item_proposer",
279
+ ner__magic_moment_detector: "ner.magic_moment_detector",
280
+ ner__scope_proposer: "ner.scope_proposer",
281
+ ner__scope_slot_filler: "ner.scope_slot_filler",
282
+ ner__suggestion_reviewer: "ner.suggestion_reviewer",
283
+ ner__sweep_scope_discoverer: "ner.sweep_scope_discoverer",
284
+ ner__sweep_scope_reference_finder: "ner.sweep_scope_reference_finder",
285
+ ner__sweep_value_miner: "ner.sweep_value_miner",
286
+ notes__organizer: "notes.organizer",
287
+ notes__page_guidance: "notes.page_guidance",
288
+ observability__tool_trace_pattern_detection: "observability.tool_trace_pattern_detection",
289
+ observability__tool_trace_triage: "observability.tool_trace_triage",
290
+ orchestras__role_describer: "orchestras.role_describer",
291
+ pdf__content_cleaner: "pdf.content_cleaner",
292
+ podcast__audience_adapter: "podcast.audience_adapter",
293
+ podcast__audio_dialogue: "podcast.audio_dialogue",
294
+ podcast__audio_english: "podcast.audio_english",
295
+ podcast__audio_persian: "podcast.audio_persian",
296
+ podcast__chapter_marker: "podcast.chapter_marker",
297
+ podcast__content_extractor: "podcast.content_extractor",
298
+ podcast__deep_research: "podcast.deep_research",
299
+ podcast__image_v1: "podcast.image_v1",
300
+ podcast__image_v2: "podcast.image_v2",
301
+ podcast__image_v3: "podcast.image_v3",
302
+ podcast__image_v4: "podcast.image_v4",
303
+ podcast__image_v5: "podcast.image_v5",
304
+ podcast__image_v6_feature: "podcast.image_v6_feature",
305
+ podcast__image_v6_feature_prompt: "podcast.image_v6_feature_prompt",
306
+ podcast__live_rewrite: "podcast.live_rewrite",
307
+ podcast__metadata: "podcast.metadata",
308
+ podcast__multihost_script: "podcast.multihost_script",
309
+ podcast__post_prep_expansion: "podcast.post_prep_expansion",
310
+ podcast__post_prep_fact_checking: "podcast.post_prep_fact_checking",
311
+ podcast__post_prep_summarization: "podcast.post_prep_summarization",
312
+ podcast__post_prep_translation: "podcast.post_prep_translation",
313
+ podcast__race_frontier: "podcast.race_frontier",
314
+ podcast__relevance_gate: "podcast.relevance_gate",
315
+ podcast__roundtable_script: "podcast.roundtable_script",
316
+ podcast__script_educational: "podcast.script_educational",
317
+ podcast__script_news: "podcast.script_news",
318
+ podcast__script_persian: "podcast.script_persian",
319
+ podcast__solo_script: "podcast.solo_script",
320
+ podcast__title_optimizer: "podcast.title_optimizer",
321
+ podcast__video_v1: "podcast.video_v1",
322
+ podcast__video_v2: "podcast.video_v2",
323
+ podcast_client__blog_writer: "podcast_client.blog_writer",
324
+ podcast_client__show_notes: "podcast_client.show_notes",
325
+ podcast_client__topic_ideas: "podcast_client.topic_ideas",
326
+ podcast_client__web_content_extractor: "podcast_client.web_content_extractor",
327
+ podcast_client__youtube_research: "podcast_client.youtube_research",
328
+ product_capture__instant_analysis: "product_capture.instant_analysis",
329
+ projects__creation_guide: "projects.creation_guide",
330
+ proof_runs__judge: "proof_runs.judge",
331
+ purpose__writer: "purpose.writer",
332
+ rag__chunk_contextualizer: "rag.chunk_contextualizer",
333
+ rag__hyde_generator: "rag.hyde_generator",
334
+ rag__pdf_page_cleaner: "rag.pdf_page_cleaner",
335
+ rag__query_expander: "rag.query_expander",
336
+ research__auto_tagger: "research.auto_tagger",
337
+ research__condenser_1: "research.condenser_1",
338
+ research__condenser_2: "research.condenser_2",
339
+ research__coverage_audit: "research.coverage_audit",
340
+ research__cross_cutting_tags: "research.cross_cutting_tags",
341
+ research__document_assembly: "research.document_assembly",
342
+ research__keyword_synthesis: "research.keyword_synthesis",
343
+ research__report: "research.report",
344
+ research__report_updater: "research.report_updater",
345
+ research__source_authority: "research.source_authority",
346
+ research__structured_page_summary: "research.structured_page_summary",
347
+ research__suggest_setup: "research.suggest_setup",
348
+ research__tag_consolidation: "research.tag_consolidation",
349
+ research_client__output_blog: "research_client.output_blog",
350
+ research_client__output_brand_profile: "research_client.output_brand_profile",
351
+ research_client__output_competitive_landscape: "research_client.output_competitive_landscape",
352
+ research_client__output_gap_analysis: "research_client.output_gap_analysis",
353
+ research_client__output_literature_review: "research_client.output_literature_review",
354
+ research_client__output_reputation_business: "research_client.output_reputation_business",
355
+ research_client__output_reputation_personal: "research_client.output_reputation_personal",
356
+ research_client__output_seo: "research_client.output_seo",
357
+ research_client__output_slides: "research_client.output_slides",
358
+ scraper__fact_check: "scraper.fact_check",
359
+ scraper__keyword_analysis: "scraper.keyword_analysis",
360
+ seo__ai_visibility_decision_analyst: "seo.ai_visibility_decision_analyst",
361
+ seo__backlink_context_assessor: "seo.backlink_context_assessor",
362
+ seo__backlink_work_planner: "seo.backlink_work_planner",
363
+ seo__business_model_verdict: "seo.business_model_verdict",
364
+ seo__competitor_classifier: "seo.competitor_classifier",
365
+ seo__competitor_opportunity_autopsy: "seo.competitor_opportunity_autopsy",
366
+ seo__competitor_page_autopsy: "seo.competitor_page_autopsy",
367
+ seo__coverage_analyst: "seo.coverage_analyst",
368
+ seo__digital_pr_reputation_adjudicator: "seo.digital_pr_reputation_adjudicator",
369
+ seo__evidence_workbench: "seo.evidence_workbench",
370
+ seo__finding_fixer: "seo.finding_fixer",
371
+ seo__guidelines_drafter: "seo.guidelines_drafter",
372
+ seo__ideal_customer_profile: "seo.ideal_customer_profile",
373
+ seo__keyword_classifier: "seo.keyword_classifier",
374
+ seo__keyword_expander: "seo.keyword_expander",
375
+ seo__keyword_researcher: "seo.keyword_researcher",
376
+ seo__keyword_serp_intent_analyst: "seo.keyword_serp_intent_analyst",
377
+ seo__landscape_brief: "seo.landscape_brief",
378
+ seo__money_map: "seo.money_map",
379
+ seo__offering_extraction: "seo.offering_extraction",
380
+ seo__offering_valuation: "seo.offering_valuation",
381
+ seo__page_analyzer: "seo.page_analyzer",
382
+ seo__page_keyword_mapper: "seo.page_keyword_mapper",
383
+ seo__press_source_request_responder: "seo.press_source_request_responder",
384
+ seo__press_story_analyst: "seo.press_story_analyst",
385
+ seo__session_rule_writer: "seo.session_rule_writer",
386
+ seo__session_stamp_proposer: "seo.session_stamp_proposer",
387
+ seo__site_intake: "seo.site_intake",
388
+ seo__site_link_authority_router: "seo.site_link_authority_router",
389
+ seo__site_strategist: "seo.site_strategist",
390
+ seo__starter_pack_proposer: "seo.starter_pack_proposer",
391
+ seo__topic_assigner: "seo.topic_assigner",
392
+ sms__owner_beta: "sms.owner_beta",
393
+ surfaces_client__binding_mapper: "surfaces_client.binding_mapper",
394
+ tasks__triage: "tasks.triage",
395
+ tool_viz__component_generator: "tool_viz.component_generator",
396
+ tools__summarize_content: "tools.summarize_content",
397
+ transcript_studio__document_edit: "transcript_studio.document_edit",
398
+ transcript_studio__scribe_live: "transcript_studio.scribe_live",
399
+ vision_interview__adversary: "vision_interview.adversary",
400
+ vision_interview__amplifier: "vision_interview.amplifier",
401
+ vision_interview__answer_tracker: "vision_interview.answer_tracker",
402
+ vision_interview__archaeologist: "vision_interview.archaeologist",
403
+ vision_interview__architect: "vision_interview.architect",
404
+ vision_interview__cartographer: "vision_interview.cartographer",
405
+ vision_interview__requirements_author: "vision_interview.requirements_author",
406
+ vision_interview__scribe: "vision_interview.scribe",
407
+ vision_interview__sounding_board: "vision_interview.sounding_board",
408
+ vision_interview__transcript_cleaner: "vision_interview.transcript_cleaner",
409
+ vision_interview__vision_author: "vision_interview.vision_author",
410
+ voice__communicator: "voice.communicator",
411
+ voice__intro: "voice.intro",
412
+ voice__owner_beta: "voice.owner_beta",
413
+ war_room__master: "war_room.master",
414
+ war_room__room: "war_room.room",
415
+ war_room__thread: "war_room.thread",
416
+ web__endpoint_family_judge: "web.endpoint_family_judge",
417
+ workflow__complex_research__keyword_synthesis: "workflow.complex_research.keyword_synthesis",
418
+ workflow__complex_research__page_summary: "workflow.complex_research.page_summary",
419
+ workflow__complex_research__report: "workflow.complex_research.report",
420
+ workflow__conductor: "workflow.conductor",
421
+ workflow__deep_research__keyword_synthesis: "workflow.deep_research.keyword_synthesis",
422
+ workflow__extract_namer: "workflow.extract_namer",
423
+ workflow__plan_design: "workflow.plan_design",
424
+ workflow__plan_input_kind_authoring: "workflow.plan_input_kind_authoring",
425
+ workflow__plan_node_type_recommender: "workflow.plan_node_type_recommender",
426
+ workflow__plan_notes_writer: "workflow.plan_notes_writer",
427
+ workflow__plan_output_kind_authoring: "workflow.plan_output_kind_authoring",
428
+ workflow__recovery_advisor: "workflow.recovery_advisor",
429
+ workflow__run_assist_suggester: "workflow.run_assist_suggester",
430
+ workflow__step_intelligence: "workflow.step_intelligence",
431
+ workflow__steward: "workflow.steward",
432
+ workflow__steward__agent_run: "workflow.steward.agent_run",
433
+ workflow__steward__data: "workflow.steward.data",
434
+ workflow__steward__decision: "workflow.steward.decision",
435
+ workflow__steward__user_input: "workflow.steward.user_input"
436
+ };
437
+ var ALL_MANDATE_KEYS = Object.values(MANDATE_KEYS);
438
+
439
+ // mandates/index.ts
440
+ var KEY_SET = new Set(ALL_MANDATE_KEYS);
441
+
442
+ // matrx/transport.ts
443
+ var MatrxApiError = class extends Error {
444
+ name = "MatrxApiError";
445
+ /** HTTP status of the failed response. */
446
+ status;
447
+ /** Machine code from the server body (`code`, or `detail.code`), when present. */
448
+ code;
449
+ /** The parsed server error body, verbatim (undefined when unparsable). */
450
+ serverDetail;
451
+ /** The request path the failure came from (server-relative). */
452
+ path;
453
+ constructor(args) {
454
+ super(
455
+ args.message ?? extractMatrxErrorMessage(args.serverDetail) ?? `HTTP ${args.status}`
456
+ );
457
+ this.status = args.status;
458
+ this.path = args.path;
459
+ this.serverDetail = args.serverDetail;
460
+ this.code = extractMatrxErrorCode(args.serverDetail);
461
+ }
462
+ };
463
+ function isRecord(value) {
464
+ return typeof value === "object" && value !== null && !Array.isArray(value);
465
+ }
466
+ function nonBlankString(value) {
467
+ return typeof value === "string" && value.trim() ? value : void 0;
468
+ }
469
+ function extractMatrxErrorMessage(serverDetail) {
470
+ if (!isRecord(serverDetail)) return void 0;
471
+ const userMessage = nonBlankString(serverDetail.user_message);
472
+ if (userMessage) return userMessage;
473
+ const message = nonBlankString(serverDetail.message);
474
+ if (message) return message;
475
+ if (Array.isArray(serverDetail.details)) {
476
+ const messages = serverDetail.details.map((entry) => {
477
+ if (!isRecord(entry)) return void 0;
478
+ const detailMessage = nonBlankString(entry.message);
479
+ if (!detailMessage) return void 0;
480
+ const field = nonBlankString(entry.field);
481
+ return field ? `${field}: ${detailMessage}` : detailMessage;
482
+ }).filter((m) => typeof m === "string");
483
+ if (messages.length > 0) return messages.join("; ");
484
+ }
485
+ const detail = serverDetail.detail;
486
+ if (isRecord(detail)) {
487
+ const detailMessage = nonBlankString(detail.message) ?? nonBlankString(detail.user_message);
488
+ if (detailMessage) return detailMessage;
489
+ }
490
+ if (typeof detail === "string" && detail.trim()) return detail;
491
+ if (Array.isArray(detail)) {
492
+ const messages = detail.map(
493
+ (entry) => isRecord(entry) ? nonBlankString(entry.msg) : void 0
494
+ ).filter((m) => typeof m === "string");
495
+ if (messages.length > 0) return messages.join("; ");
496
+ }
497
+ return void 0;
498
+ }
499
+ function extractMatrxErrorCode(serverDetail) {
500
+ if (!isRecord(serverDetail)) return null;
501
+ const topLevel = nonBlankString(serverDetail.code);
502
+ if (topLevel) return topLevel;
503
+ const detail = serverDetail.detail;
504
+ if (isRecord(detail)) {
505
+ const nested = nonBlankString(detail.code);
506
+ if (nested) return nested;
507
+ }
508
+ return null;
509
+ }
510
+
511
+ // matrx/conversation.ts
512
+ function mintMatrxConversationId() {
513
+ return crypto.randomUUID();
514
+ }
515
+ function newStoredConversationStart(conversationId) {
516
+ return {
517
+ conversation_id: conversationId ?? mintMatrxConversationId(),
518
+ is_new: true,
519
+ store: true
520
+ };
521
+ }
522
+
523
+ // stream/ndjson.ts
524
+ var DEFAULT_MATRX_NDJSON_READ_AHEAD = 64;
525
+ function isRecord2(value) {
526
+ return typeof value === "object" && value !== null && !Array.isArray(value);
527
+ }
528
+ function normalizeMatrxStreamEnvelope(value) {
529
+ if (!isRecord2(value)) return null;
530
+ if (typeof value.event === "string") {
531
+ const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
532
+ const streamId = typeof value.stream_id === "string" ? value.stream_id : void 0;
533
+ return {
534
+ event: value.event,
535
+ data: value.data,
536
+ ...streamId === void 0 ? {} : { stream_id: streamId },
537
+ ...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
538
+ };
539
+ }
540
+ if (value.e === "c" && typeof value.t === "string") {
541
+ const streamId = typeof value.stream_id === "string" ? value.stream_id : void 0;
542
+ const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
543
+ return {
544
+ event: "chunk",
545
+ data: { text: value.t },
546
+ ...streamId === void 0 ? {} : { stream_id: streamId },
547
+ ...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
548
+ };
549
+ }
550
+ if (value.e === "r" && typeof value.t === "string") {
551
+ const streamId = typeof value.stream_id === "string" ? value.stream_id : void 0;
552
+ const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
553
+ return {
554
+ event: "reasoning_chunk",
555
+ data: { text: value.t },
556
+ ...streamId === void 0 ? {} : { stream_id: streamId },
557
+ ...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
558
+ };
559
+ }
560
+ return null;
561
+ }
562
+ function createMatrxNdjsonFramer(options = {}) {
563
+ const decoder = new TextDecoder();
564
+ let buffer = "";
565
+ let lineNumber = 0;
566
+ let finished = false;
567
+ const assertOpen = () => {
568
+ if (finished) throw new Error("Matrx NDJSON framer is already finished");
569
+ };
570
+ const parseLine = (line, atCompletion) => {
571
+ const currentLineNumber = ++lineNumber;
572
+ const trimmed = line.trim();
573
+ if (!trimmed) return null;
574
+ let parsed;
575
+ try {
576
+ parsed = JSON.parse(trimmed);
577
+ } catch (error) {
578
+ options.onMalformedLine?.({
579
+ line: trimmed,
580
+ error,
581
+ lineNumber: currentLineNumber,
582
+ atCompletion
583
+ });
584
+ return null;
585
+ }
586
+ const envelope = normalizeMatrxStreamEnvelope(parsed);
587
+ if (!envelope) {
588
+ options.onUnknownEnvelope?.(parsed);
589
+ return null;
590
+ }
591
+ options.onValidEnvelope?.({
592
+ raw: parsed,
593
+ envelope,
594
+ line: trimmed,
595
+ lineNumber: currentLineNumber,
596
+ atCompletion
597
+ });
598
+ return envelope;
599
+ };
600
+ const pushDecodedText = (fragment) => {
601
+ buffer += fragment;
602
+ const lines = buffer.split("\n");
603
+ buffer = lines.pop() ?? "";
604
+ const envelopes = [];
605
+ for (const line of lines) {
606
+ const envelope = parseLine(line, false);
607
+ if (envelope) envelopes.push(envelope);
608
+ }
609
+ return envelopes;
610
+ };
611
+ return {
612
+ pushText(fragment) {
613
+ assertOpen();
614
+ return pushDecodedText(decoder.decode() + fragment);
615
+ },
616
+ pushBytes(fragment) {
617
+ assertOpen();
618
+ return pushDecodedText(decoder.decode(fragment, { stream: true }));
619
+ },
620
+ finish() {
621
+ assertOpen();
622
+ finished = true;
623
+ const envelopes = pushDecodedText(decoder.decode());
624
+ if (buffer.length > 0) {
625
+ const envelope = parseLine(buffer, true);
626
+ buffer = "";
627
+ if (envelope) envelopes.push(envelope);
628
+ }
629
+ return envelopes;
630
+ }
631
+ };
632
+ }
633
+ function readAheadLimit(value) {
634
+ const limit = value ?? DEFAULT_MATRX_NDJSON_READ_AHEAD;
635
+ if (!Number.isSafeInteger(limit) || limit < 1) {
636
+ throw new RangeError("maxReadAhead must be a positive safe integer");
637
+ }
638
+ return limit;
639
+ }
640
+ async function* readMatrxNdjsonStream(body, options = {}) {
641
+ const maxReadAhead = readAheadLimit(options.maxReadAhead);
642
+ const queue = [];
643
+ let queuedEventCount = 0;
644
+ let wakeConsumer = null;
645
+ let wakeProducer = null;
646
+ let readerFinished = false;
647
+ let consumerClosed = false;
648
+ const wakeWaitingConsumer = () => {
649
+ const wake = wakeConsumer;
650
+ wakeConsumer = null;
651
+ wake?.();
652
+ };
653
+ const wakeWaitingProducer = () => {
654
+ const wake = wakeProducer;
655
+ wakeProducer = null;
656
+ wake?.();
657
+ };
658
+ const enqueueTerminal = (item) => {
659
+ if (consumerClosed) return;
660
+ queue.push(item);
661
+ wakeWaitingConsumer();
662
+ };
663
+ const enqueueEvent = async (value) => {
664
+ while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
665
+ await new Promise((resolve2) => {
666
+ wakeProducer = resolve2;
667
+ });
668
+ }
669
+ if (consumerClosed || options.signal?.aborted) return false;
670
+ queue.push({ kind: "event", value });
671
+ queuedEventCount += 1;
672
+ wakeWaitingConsumer();
673
+ return true;
674
+ };
675
+ const waitForReadCapacity = async () => {
676
+ while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
677
+ await new Promise((resolve2) => {
678
+ wakeProducer = resolve2;
679
+ });
680
+ }
681
+ return !consumerClosed && !options.signal?.aborted;
682
+ };
683
+ const reader = body.getReader();
684
+ const framer = createMatrxNdjsonFramer(options);
685
+ const onAbort = () => {
686
+ wakeWaitingProducer();
687
+ wakeWaitingConsumer();
688
+ void reader.cancel(options.signal?.reason).catch(() => void 0);
689
+ };
690
+ options.signal?.addEventListener("abort", onAbort, { once: true });
691
+ if (options.signal?.aborted) onAbort();
692
+ const readerPromise = (async () => {
693
+ try {
694
+ while (!options.signal?.aborted && !consumerClosed) {
695
+ if (!await waitForReadCapacity()) return;
696
+ const { value, done } = await reader.read();
697
+ if (done) break;
698
+ for (const envelope of framer.pushBytes(value)) {
699
+ if (!await enqueueEvent(envelope)) return;
700
+ }
701
+ }
702
+ if (!options.signal?.aborted && !consumerClosed) {
703
+ for (const envelope of framer.finish()) {
704
+ if (!await enqueueEvent(envelope)) return;
705
+ }
706
+ }
707
+ } catch (error) {
708
+ const aborted = options.signal?.aborted || consumerClosed || error instanceof Error && error.name === "AbortError";
709
+ if (!aborted) enqueueTerminal({ kind: "error", error });
710
+ } finally {
711
+ readerFinished = true;
712
+ reader.releaseLock();
713
+ enqueueTerminal({ kind: "done" });
714
+ }
715
+ })();
716
+ try {
717
+ while (true) {
718
+ if (queue.length === 0) {
719
+ if (options.signal?.aborted || readerFinished) return;
720
+ await new Promise((resolve2) => {
721
+ wakeConsumer = resolve2;
722
+ });
723
+ }
724
+ const item = queue.shift();
725
+ if (item?.kind === "event") queuedEventCount -= 1;
726
+ wakeWaitingProducer();
727
+ if (!item || item.kind === "done") return;
728
+ if (item.kind === "error") throw item.error;
729
+ yield item.value;
730
+ }
731
+ } finally {
732
+ consumerClosed = true;
733
+ wakeWaitingProducer();
734
+ wakeWaitingConsumer();
735
+ options.signal?.removeEventListener("abort", onAbort);
736
+ if (!readerFinished) {
737
+ await reader.cancel().catch(() => void 0);
738
+ }
739
+ await readerPromise;
740
+ }
741
+ }
742
+
743
+ // matrx/internal.ts
744
+ function encodePathSegment(value) {
745
+ return encodeURIComponent(value);
746
+ }
747
+ function buildQuery(params) {
748
+ const search = new URLSearchParams();
749
+ for (const [key, value] of Object.entries(params)) {
750
+ if (value === void 0) continue;
751
+ if (Array.isArray(value)) {
752
+ for (const entry of value) search.append(key, entry);
753
+ } else {
754
+ search.append(key, String(value));
755
+ }
756
+ }
757
+ const encoded = search.toString();
758
+ return encoded ? `?${encoded}` : "";
759
+ }
760
+ async function readServerDetail(response) {
761
+ try {
762
+ return await response.json();
763
+ } catch {
764
+ return void 0;
765
+ }
766
+ }
767
+ async function throwApiError(path, response) {
768
+ throw new MatrxApiError({
769
+ status: response.status,
770
+ path,
771
+ serverDetail: await readServerDetail(response)
772
+ });
773
+ }
774
+ async function requestJson(transport, path, options) {
775
+ const hasBody = options.method !== "GET" && options.body !== void 0;
776
+ const response = await transport.fetch(path, {
777
+ method: options.method,
778
+ headers: hasBody ? { "Content-Type": "application/json" } : {},
779
+ ...hasBody ? { body: JSON.stringify(options.body) } : {},
780
+ ...options.signal ? { signal: options.signal } : {}
781
+ });
782
+ if (!response.ok) return throwApiError(path, response);
783
+ return await response.json();
784
+ }
785
+ function toRunHandle(response, options) {
786
+ return {
787
+ requestId: response.headers.get("X-Request-ID"),
788
+ conversationId: response.headers.get("X-Conversation-ID"),
789
+ events: readMatrxNdjsonStream(response.body, {
790
+ ...options.signal ? { signal: options.signal } : {},
791
+ ...options.maxReadAhead !== void 0 ? { maxReadAhead: options.maxReadAhead } : {},
792
+ ...options.onMalformedLine ? { onMalformedLine: options.onMalformedLine } : {},
793
+ ...options.onUnknownEnvelope ? { onUnknownEnvelope: options.onUnknownEnvelope } : {},
794
+ ...options.onValidEnvelope ? { onValidEnvelope: options.onValidEnvelope } : {}
795
+ }),
796
+ response
797
+ };
798
+ }
799
+ async function requestStream(transport, path, options) {
800
+ const hasBody = options.method !== "GET" && options.body !== void 0;
801
+ const response = await transport.fetch(path, {
802
+ method: options.method,
803
+ headers: {
804
+ ...hasBody ? { "Content-Type": "application/json" } : {},
805
+ ...options.headers
806
+ },
807
+ ...hasBody ? { body: JSON.stringify(options.body) } : {},
808
+ ...options.signal ? { signal: options.signal } : {}
809
+ });
810
+ if (!response.ok) return throwApiError(path, response);
811
+ if (!response.body) {
812
+ throw new MatrxApiError({
813
+ status: response.status,
814
+ path,
815
+ serverDetail: { code: "missing_response_body" },
816
+ message: "The streaming response carried no body."
817
+ });
818
+ }
819
+ return response;
820
+ }
821
+
822
+ // matrx/run.ts
823
+ async function streamCall(transport, path, body, options) {
824
+ const response = await requestStream(transport, path, {
825
+ method: "POST",
826
+ // This client IS the streaming path — `stream: true` always, last so a
827
+ // caller-supplied value can never flip the response off NDJSON.
828
+ body: { ...body, stream: true },
829
+ ...options.signal ? { signal: options.signal } : {}
830
+ });
831
+ return toRunHandle(response, options);
832
+ }
833
+ function startMandateRun(transport, mandateKey, request, options = {}) {
834
+ return streamCall(
835
+ transport,
836
+ `/ai/mandates/${encodePathSegment(mandateKey)}`,
837
+ request,
838
+ options
839
+ );
840
+ }
841
+ function cancelAgentRun(transport, requestId, options = {}) {
842
+ const query = buildQuery(
843
+ options.mode === "interrupt" ? { mode: "interrupt" } : {}
844
+ );
845
+ return requestJson(
846
+ transport,
847
+ `/ai/cancel/${encodePathSegment(requestId)}${query}`,
848
+ {
849
+ method: "POST",
850
+ ...options.signal ? { signal: options.signal } : {}
851
+ }
852
+ );
853
+ }
854
+
855
+ // stream/sse.ts
856
+ var FRAME_SEPARATOR = /\r\n\r\n|\n\n|\r\r/;
857
+ var LINE_SEPARATOR = /\r\n|\n|\r/;
858
+ function parseMatrxSseFrame(frame) {
859
+ let event = "message";
860
+ let id = null;
861
+ const dataLines = [];
862
+ let sawData = false;
863
+ for (const line of frame.split(LINE_SEPARATOR)) {
864
+ if (line.startsWith(":")) continue;
865
+ if (line.startsWith("event:")) event = line.slice(6).trim();
866
+ else if (line.startsWith("data:")) {
867
+ sawData = true;
868
+ dataLines.push(line.slice(5).replace(/^ /, ""));
869
+ } else if (line.startsWith("id:")) id = line.slice(3).trim();
870
+ }
871
+ const seqCandidate = id !== null && id !== "" ? Number(id) : NaN;
872
+ const seq = Number.isSafeInteger(seqCandidate) && seqCandidate >= 0 ? seqCandidate : null;
873
+ return { event, id, seq, data: sawData ? dataLines.join("\n") : null };
874
+ }
875
+ function createMatrxSseFramer() {
876
+ let buffer = "";
877
+ return {
878
+ push(chunk) {
879
+ buffer += chunk;
880
+ const frames = [];
881
+ for (; ; ) {
882
+ const sep = FRAME_SEPARATOR.exec(buffer);
883
+ if (sep === null) break;
884
+ const frame = buffer.slice(0, sep.index);
885
+ buffer = buffer.slice(sep.index + sep[0].length);
886
+ frames.push(parseMatrxSseFrame(frame));
887
+ }
888
+ return frames;
889
+ },
890
+ flush() {
891
+ const rest = buffer;
892
+ buffer = "";
893
+ return { incomplete: rest.length > 0 ? rest : null };
894
+ }
895
+ };
896
+ }
897
+ async function* readMatrxSseStream(stream, options = {}) {
898
+ const reader = stream.getReader();
899
+ const decoder = new TextDecoder();
900
+ const framer = createMatrxSseFramer();
901
+ try {
902
+ for (; ; ) {
903
+ const { value, done } = await reader.read();
904
+ if (done) break;
905
+ const frames = framer.push(decoder.decode(value, { stream: true }));
906
+ for (const frame of frames) yield frame;
907
+ }
908
+ const tail = framer.push(decoder.decode());
909
+ for (const frame of tail) yield frame;
910
+ const { incomplete } = framer.flush();
911
+ if (incomplete !== null) options.onIncomplete?.(incomplete);
912
+ } finally {
913
+ reader.releaseLock();
914
+ }
915
+ }
916
+
917
+ // matrx/operations.ts
918
+ var RUNTIME_STATUSES = /* @__PURE__ */ new Set([
919
+ "pending",
920
+ "running",
921
+ "paused",
922
+ "waiting_input",
923
+ "completed",
924
+ "failed",
925
+ "cancelled"
926
+ ]);
927
+ async function getRuntimeOperationStatus(transport, requestId, options = {}) {
928
+ try {
929
+ return await requestJson(
930
+ transport,
931
+ `/runtime/operations/${encodePathSegment(requestId)}`,
932
+ { method: "GET", ...options.signal ? { signal: options.signal } : {} }
933
+ );
934
+ } catch (error) {
935
+ if (error instanceof MatrxApiError && error.status === 404) return null;
936
+ throw error;
937
+ }
938
+ }
939
+ function parseEndStatus(data) {
940
+ if (data === null) return null;
941
+ try {
942
+ const parsed = JSON.parse(data);
943
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.status === "string") {
944
+ const status = parsed.status;
945
+ return RUNTIME_STATUSES.has(status) ? status : null;
946
+ }
947
+ } catch {
948
+ }
949
+ return null;
950
+ }
951
+ async function* followRuntimeOperationEvents(transport, executionId, options = {}) {
952
+ let cursor = options.lastEventSeq ?? 0;
953
+ const headers = { Accept: "text/event-stream" };
954
+ if (cursor > 0) headers["Last-Event-ID"] = String(cursor);
955
+ const response = await requestStream(
956
+ transport,
957
+ `/runtime/executions/${encodePathSegment(executionId)}/events/stream`,
958
+ {
959
+ method: "GET",
960
+ headers,
961
+ ...options.signal ? { signal: options.signal } : {}
962
+ }
963
+ );
964
+ const frames = readMatrxSseStream(
965
+ response.body,
966
+ options.onIncomplete ? { onIncomplete: options.onIncomplete } : {}
967
+ );
968
+ for await (const frame of frames) {
969
+ if (frame.event === "end") {
970
+ yield { type: "end", status: parseEndStatus(frame.data), cursor };
971
+ return;
972
+ }
973
+ if (frame.event === "execution_event" && frame.data !== null) {
974
+ let event;
975
+ try {
976
+ event = JSON.parse(frame.data);
977
+ } catch (error) {
978
+ options.onMalformedFrame?.(frame, error);
979
+ yield { type: "liveness", cursor };
980
+ continue;
981
+ }
982
+ if (frame.seq !== null && frame.seq > cursor) cursor = frame.seq;
983
+ yield { type: "event", event, seq: frame.seq, cursor };
984
+ continue;
985
+ }
986
+ yield { type: "liveness", cursor };
987
+ }
988
+ }
989
+ async function followRuntimeOperationToEnd(transport, executionId, options) {
990
+ const stallTimeoutMs = options.stallTimeoutMs ?? 45e3;
991
+ const reconnectLimit = options.reconnectLimit ?? 60;
992
+ const reconnectDelayMs = options.reconnectDelayMs ?? 2e3;
993
+ const outer = options.signal;
994
+ let cursor = options.lastEventSeq ?? 0;
995
+ let failures = 0;
996
+ while (!outer?.aborted && failures < reconnectLimit) {
997
+ const attempt = new AbortController();
998
+ const onOuterAbort = () => attempt.abort();
999
+ outer?.addEventListener("abort", onOuterAbort, { once: true });
1000
+ let stallTimer = null;
1001
+ const armStall = () => {
1002
+ if (stallTimer !== null) clearTimeout(stallTimer);
1003
+ stallTimer = setTimeout(() => attempt.abort(), stallTimeoutMs);
1004
+ };
1005
+ try {
1006
+ const items = followRuntimeOperationEvents(transport, executionId, {
1007
+ lastEventSeq: cursor,
1008
+ signal: attempt.signal,
1009
+ ...options.onMalformedFrame ? { onMalformedFrame: options.onMalformedFrame } : {}
1010
+ });
1011
+ armStall();
1012
+ for await (const item of items) {
1013
+ armStall();
1014
+ failures = 0;
1015
+ cursor = item.cursor;
1016
+ if (item.type === "end") {
1017
+ return { ended: true, status: item.status };
1018
+ }
1019
+ if (item.type === "event") {
1020
+ options.onEvent(item.event, item.seq);
1021
+ }
1022
+ }
1023
+ failures += 1;
1024
+ } catch (error) {
1025
+ if (outer?.aborted) break;
1026
+ failures += 1;
1027
+ options.onAttemptError?.(error);
1028
+ } finally {
1029
+ if (stallTimer !== null) clearTimeout(stallTimer);
1030
+ outer?.removeEventListener("abort", onOuterAbort);
1031
+ }
1032
+ if (!outer?.aborted && failures < reconnectLimit) {
1033
+ await new Promise((r) => setTimeout(r, reconnectDelayMs));
1034
+ }
1035
+ }
1036
+ return { ended: false, status: null };
1037
+ }
1038
+ async function rejoinRuntimeOperation(transport, requestId, options = {}) {
1039
+ const response = await requestStream(
1040
+ transport,
1041
+ `/runtime/operations/${encodePathSegment(requestId)}/rejoin`,
1042
+ {
1043
+ method: "POST",
1044
+ // The route takes no body model; the reference client posts an empty
1045
+ // JSON object. Match it so proxies see an ordinary JSON POST.
1046
+ body: {},
1047
+ ...options.signal ? { signal: options.signal } : {}
1048
+ }
1049
+ );
1050
+ return toRunHandle(response, options);
1051
+ }
1052
+
1053
+ // content-transfer/index.ts
1054
+ var SupersededRunError = class extends Error {
1055
+ constructor() {
1056
+ super("A newer AI preparation started before this result settled.");
1057
+ }
1058
+ };
1059
+ function resolve(value) {
1060
+ return typeof value === "function" ? value() : value;
1061
+ }
1062
+ function deepFreeze(value) {
1063
+ if (ArrayBuffer.isView(value)) return value;
1064
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
1065
+ Object.freeze(value);
1066
+ for (const nested of Object.values(value)) deepFreeze(nested);
1067
+ }
1068
+ return value;
1069
+ }
1070
+ function isDeepFrozen(value, seen = /* @__PURE__ */ new WeakSet()) {
1071
+ if (!value || typeof value !== "object" || ArrayBuffer.isView(value))
1072
+ return true;
1073
+ if (seen.has(value)) return true;
1074
+ seen.add(value);
1075
+ return Object.isFrozen(value) && Object.values(value).every((nested) => isDeepFrozen(nested, seen));
1076
+ }
1077
+ function descriptionForCoverage(snapshot, draft) {
1078
+ const { coverage } = snapshot;
1079
+ const total = coverage.total === null ? "unknown total" : `${coverage.total} total`;
1080
+ const offered = draft.payload.kind === "rows" ? `${draft.payload.rows.length} prepared rows` : "one prepared document";
1081
+ return `snapshot ${coverage.status}: ${coverage.included} included, ${total}; offered ${offered} from ${draft.sourceId}@${draft.sourceRevision}, draft revision ${draft.revision}${coverage.reason ? `; ${coverage.reason}` : ""}`;
1082
+ }
1083
+ function descriptionForOmissions(draft) {
1084
+ if (draft.omissions.length === 0)
1085
+ return "No pre-AI exclusions or reductions were recorded in this prepared draft.";
1086
+ return draft.omissions.map(
1087
+ (o) => `${o.path || "document"}: ${o.reason}${o.count === void 0 ? "" : ` (${o.count})`}`
1088
+ ).join("; ");
1089
+ }
1090
+ function visibleAssistantText(content) {
1091
+ if (typeof content === "string") return content.trim() || null;
1092
+ if (!Array.isArray(content)) return null;
1093
+ const parts = content.flatMap((part) => {
1094
+ if (!part || typeof part !== "object" || Array.isArray(part)) return [];
1095
+ const block = part;
1096
+ return block.type === "text" && typeof block.text === "string" ? [block.text] : [];
1097
+ });
1098
+ return parts.join("\n\n").trim() || null;
1099
+ }
1100
+ function responseMessageId(metadata) {
1101
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata))
1102
+ return null;
1103
+ const value = metadata.response_message_id;
1104
+ return typeof value === "string" && value.length > 0 ? value : null;
1105
+ }
1106
+ function draftFromAssistant(source, text, identity) {
1107
+ const edited = (0, import_content_transfer.editDraft)(source, { kind: "markdown", text });
1108
+ const reducedBy = (0, import_content_transfer.serialize)(source, "markdown").plainText.length - text.length;
1109
+ return deepFreeze({
1110
+ ...edited,
1111
+ manuallyEdited: source.manuallyEdited,
1112
+ omissions: [
1113
+ ...edited.omissions,
1114
+ ...reducedBy > 0 ? [
1115
+ {
1116
+ path: "/ai/content",
1117
+ reason: "truncated",
1118
+ count: reducedBy
1119
+ }
1120
+ ] : []
1121
+ ],
1122
+ provenance: [
1123
+ ...edited.provenance.slice(0, -1),
1124
+ {
1125
+ kind: "ai",
1126
+ operationId: identity.requestId,
1127
+ description: `AI preparation of ${source.sourceId}@${source.sourceRevision}; source omissions remain separately recorded.`
1128
+ }
1129
+ ]
1130
+ });
1131
+ }
1132
+ function assertCoherent(snapshot, draft) {
1133
+ if (!isDeepFrozen(snapshot) || !isDeepFrozen(draft))
1134
+ throw new Error(
1135
+ "Alchemy requires the deeply frozen Snapshot and Draft produced by @ai-matrx/kit/content-transfer."
1136
+ );
1137
+ if (draft.snapshotId !== snapshot.id || draft.sourceId !== snapshot.sourceId || draft.sourceRevision !== snapshot.revision)
1138
+ throw new Error(
1139
+ "The prepared draft does not belong to this captured snapshot."
1140
+ );
1141
+ }
1142
+ function assertIdentitySource(identity, source) {
1143
+ if (!isDeepFrozen(source))
1144
+ throw new Error(
1145
+ "Alchemy recovery requires the deeply frozen Draft produced by @ai-matrx/kit/content-transfer."
1146
+ );
1147
+ if (identity.snapshotId !== source.snapshotId || identity.sourceId !== source.sourceId || identity.sourceRevision !== source.sourceRevision || identity.draftRevision !== source.revision) {
1148
+ throw new Error(
1149
+ "The recovery identity does not belong to this frozen prepared draft."
1150
+ );
1151
+ }
1152
+ }
1153
+ function errorMessage(error) {
1154
+ return error instanceof Error && error.message ? error.message : "Unknown stream failure.";
1155
+ }
1156
+ function detached(identity, message) {
1157
+ return { status: "detached", identity, draft: null, message };
1158
+ }
1159
+ async function consume(handle, afterAwait, onEvent) {
1160
+ for await (const event of handle.events) {
1161
+ afterAwait();
1162
+ onEvent?.(event);
1163
+ }
1164
+ afterAwait();
1165
+ }
1166
+ function createMatrxContentTransferAdapter(options) {
1167
+ let latestGeneration = 0;
1168
+ const transport = () => resolve(options.transport);
1169
+ const organizationId = () => resolve(options.organizationId);
1170
+ let activeGeneration = null;
1171
+ const inGeneration = async (outer, run) => {
1172
+ activeGeneration?.abort();
1173
+ const controller = new AbortController();
1174
+ activeGeneration = controller;
1175
+ const generation = ++latestGeneration;
1176
+ const abort = () => controller.abort(outer?.reason);
1177
+ if (outer?.aborted) abort();
1178
+ else outer?.addEventListener("abort", abort, { once: true });
1179
+ try {
1180
+ return await run(generation, controller.signal);
1181
+ } finally {
1182
+ outer?.removeEventListener("abort", abort);
1183
+ if (activeGeneration === controller) activeGeneration = null;
1184
+ }
1185
+ };
1186
+ const check = (generation) => {
1187
+ if (generation !== latestGeneration) throw new SupersededRunError();
1188
+ activeGeneration?.signal.throwIfAborted();
1189
+ };
1190
+ const readVisibleAssistant = async (identity, generation) => {
1191
+ const requestResult = await options.supabase.schema("chat").from("request").select("id, metadata, iteration").eq("user_request_id", identity.requestId).eq("conversation_id", identity.conversationId).is("deleted_at", null).not("metadata->>response_message_id", "is", null).order("iteration", { ascending: false }).limit(1);
1192
+ check(generation);
1193
+ if (requestResult.error)
1194
+ throw new Error(
1195
+ requestResult.error.message || "Could not read the persisted AI request."
1196
+ );
1197
+ const messageId = responseMessageId(requestResult.data?.[0]?.metadata);
1198
+ if (!messageId)
1199
+ throw new Error(
1200
+ "The completed AI request has no persisted response message link yet."
1201
+ );
1202
+ const messageResult = await options.supabase.schema("chat").from("message").select("id, content").eq("id", messageId).eq("conversation_id", identity.conversationId).eq("role", "assistant").is("deleted_at", null).eq("is_visible_to_user", true).limit(1);
1203
+ check(generation);
1204
+ if (messageResult.error)
1205
+ throw new Error(
1206
+ messageResult.error.message || "Could not read the prepared AI result."
1207
+ );
1208
+ const exact = messageResult.data?.find((row) => row.id === messageId);
1209
+ return exact ? visibleAssistantText(exact.content) : null;
1210
+ };
1211
+ const locate = async (identity, generation, signal) => {
1212
+ const result = await getRuntimeOperationStatus(
1213
+ transport(),
1214
+ identity.requestId,
1215
+ signal ? { signal } : {}
1216
+ );
1217
+ check(generation);
1218
+ const exact = result?.operations.find(
1219
+ (operation) => operation.request_id === identity.requestId && operation.link_kind === "conversation" && operation.link_id === identity.conversationId
1220
+ ) ?? null;
1221
+ if (!exact && result?.operation_count)
1222
+ throw new Error(
1223
+ "The durable operation identity does not match this stored conversation."
1224
+ );
1225
+ return exact;
1226
+ };
1227
+ const recoverInGeneration = async (generation, identity, source, onProgress, signal) => {
1228
+ try {
1229
+ assertIdentitySource(identity, source);
1230
+ check(generation);
1231
+ let operation = await locate(identity, generation, signal);
1232
+ if (!operation)
1233
+ return {
1234
+ status: "unavailable",
1235
+ identity,
1236
+ draft: null,
1237
+ message: "The durable operation is not available to this account yet."
1238
+ };
1239
+ let resolvedIdentity = deepFreeze({
1240
+ ...identity,
1241
+ executionId: operation.execution_id
1242
+ });
1243
+ if (!operation.is_terminal) {
1244
+ onProgress?.({ ...resolvedIdentity, status: operation.status });
1245
+ const settled = await followRuntimeOperationToEnd(
1246
+ transport(),
1247
+ operation.execution_id,
1248
+ {
1249
+ ...signal ? { signal } : {},
1250
+ lastEventSeq: operation.last_event_seq,
1251
+ onEvent: (event, seq) => {
1252
+ if (generation !== latestGeneration || signal?.aborted) return;
1253
+ options.onRuntimeEvent?.(event, seq);
1254
+ }
1255
+ }
1256
+ );
1257
+ check(generation);
1258
+ if (!settled.ended || settled.status === null)
1259
+ return detached(
1260
+ resolvedIdentity,
1261
+ "The lifecycle stream detached; the operation remains recoverable from this request."
1262
+ );
1263
+ const refreshed = await locate(identity, generation, signal);
1264
+ if (!refreshed)
1265
+ return detached(
1266
+ resolvedIdentity,
1267
+ "The settled operation is temporarily unavailable; retry recovery with this request."
1268
+ );
1269
+ operation = refreshed;
1270
+ resolvedIdentity = deepFreeze({
1271
+ ...identity,
1272
+ executionId: operation.execution_id
1273
+ });
1274
+ }
1275
+ onProgress?.({ ...resolvedIdentity, status: operation.status });
1276
+ if (operation.status === "cancelled")
1277
+ return {
1278
+ status: "cancelled",
1279
+ identity: resolvedIdentity,
1280
+ draft: null,
1281
+ message: "The AI preparation was cancelled. Any partial output was not applied."
1282
+ };
1283
+ if (operation.status !== "completed")
1284
+ return {
1285
+ status: "failed",
1286
+ identity: resolvedIdentity,
1287
+ draft: null,
1288
+ message: typeof operation.error?.message === "string" ? operation.error.message : "The AI preparation did not complete."
1289
+ };
1290
+ const text = await readVisibleAssistant(resolvedIdentity, generation);
1291
+ check(generation);
1292
+ if (!text)
1293
+ return {
1294
+ status: "unavailable",
1295
+ identity: resolvedIdentity,
1296
+ draft: null,
1297
+ message: "The exact persisted assistant result is not visible yet."
1298
+ };
1299
+ const draft = draftFromAssistant(source, text, resolvedIdentity);
1300
+ check(generation);
1301
+ return {
1302
+ status: "completed",
1303
+ identity: resolvedIdentity,
1304
+ draft,
1305
+ message: null
1306
+ };
1307
+ } catch (error) {
1308
+ return detached(
1309
+ identity,
1310
+ error instanceof SupersededRunError ? error.message : `Recovery detached: ${errorMessage(error)} You can retry with this request.`
1311
+ );
1312
+ }
1313
+ };
1314
+ return {
1315
+ async launch(input) {
1316
+ return inGeneration(input.signal, async (generation, signal) => {
1317
+ assertCoherent(input.snapshot, input.draft);
1318
+ const conversation = newStoredConversationStart();
1319
+ input.onProgress?.({
1320
+ requestId: null,
1321
+ conversationId: conversation.conversation_id,
1322
+ executionId: null,
1323
+ status: "starting"
1324
+ });
1325
+ const preparedContent = (0, import_content_transfer.serialize)(input.draft, "markdown").plainText;
1326
+ let identity = null;
1327
+ try {
1328
+ const handle = await startMandateRun(
1329
+ transport(),
1330
+ MANDATE_KEYS.alchemy__prepare_content,
1331
+ {
1332
+ ...conversation,
1333
+ organization_id: organizationId(),
1334
+ source_app: options.sourceApp,
1335
+ source_feature: `mandate:${MANDATE_KEYS.alchemy__prepare_content}`,
1336
+ user_input: input.instruction,
1337
+ variables: {
1338
+ prepared_content: preparedContent,
1339
+ content_label: input.snapshot.label,
1340
+ coverage_description: descriptionForCoverage(
1341
+ input.snapshot,
1342
+ input.draft
1343
+ ),
1344
+ omission_description: descriptionForOmissions(input.draft)
1345
+ }
1346
+ },
1347
+ { signal }
1348
+ );
1349
+ if (!handle.requestId)
1350
+ throw new Error(
1351
+ "The Matrx server did not return X-Request-ID for the preparation run."
1352
+ );
1353
+ identity = deepFreeze({
1354
+ requestId: handle.requestId,
1355
+ conversationId: handle.conversationId ?? conversation.conversation_id,
1356
+ executionId: null,
1357
+ snapshotId: input.snapshot.id,
1358
+ sourceId: input.draft.sourceId,
1359
+ sourceRevision: input.draft.sourceRevision,
1360
+ draftRevision: input.draft.revision
1361
+ });
1362
+ assertIdentitySource(identity, input.draft);
1363
+ check(generation);
1364
+ input.onProgress?.({ ...identity, status: "streaming" });
1365
+ await consume(handle, () => check(generation), options.onStreamEvent);
1366
+ check(generation);
1367
+ const result = await recoverInGeneration(
1368
+ generation,
1369
+ identity,
1370
+ input.draft,
1371
+ input.onProgress,
1372
+ signal
1373
+ );
1374
+ check(generation);
1375
+ return result;
1376
+ } catch (error) {
1377
+ if (!identity) throw error;
1378
+ return detached(
1379
+ identity,
1380
+ error instanceof SupersededRunError ? error.message : `The local stream detached after the server accepted the request: ${errorMessage(error)} Server work was not cancelled; retry recovery with this request.`
1381
+ );
1382
+ }
1383
+ });
1384
+ },
1385
+ async recover(identity, source, onProgress, signal) {
1386
+ return inGeneration(signal, async (generation, signal2) => {
1387
+ assertIdentitySource(identity, source);
1388
+ const result = await recoverInGeneration(
1389
+ generation,
1390
+ identity,
1391
+ source,
1392
+ onProgress,
1393
+ signal2
1394
+ );
1395
+ return generation === latestGeneration ? result : detached(
1396
+ identity,
1397
+ "A newer AI preparation started before this result settled."
1398
+ );
1399
+ });
1400
+ },
1401
+ async rejoin(identity, source, onProgress, signal) {
1402
+ return inGeneration(signal, async (generation, signal2) => {
1403
+ assertIdentitySource(identity, source);
1404
+ try {
1405
+ const handle = await rejoinRuntimeOperation(
1406
+ transport(),
1407
+ identity.requestId,
1408
+ signal2 ? { signal: signal2 } : {}
1409
+ );
1410
+ check(generation);
1411
+ await consume(handle, () => check(generation), options.onStreamEvent);
1412
+ check(generation);
1413
+ } catch (error) {
1414
+ if (!(error instanceof MatrxApiError && error.status === 409))
1415
+ return detached(
1416
+ identity,
1417
+ error instanceof SupersededRunError ? error.message : `Live rejoin detached: ${errorMessage(error)} You can retry durable recovery with this request.`
1418
+ );
1419
+ }
1420
+ const result = await recoverInGeneration(
1421
+ generation,
1422
+ identity,
1423
+ source,
1424
+ onProgress,
1425
+ signal2
1426
+ );
1427
+ return generation === latestGeneration ? result : detached(
1428
+ identity,
1429
+ "A newer AI preparation started before this result settled."
1430
+ );
1431
+ });
1432
+ },
1433
+ cancel(requestId) {
1434
+ return cancelAgentRun(transport(), requestId);
1435
+ }
1436
+ };
1437
+ }
1438
+
1439
+ // content-transfer/react/index.tsx
1440
+ var import_jsx_runtime = require("react/jsx-runtime");
1441
+ function createAiSession(options, onProgress) {
1442
+ const adapter = createMatrxContentTransferAdapter(options);
1443
+ let retainedIdentity = null;
1444
+ let retainedSource = null;
1445
+ let activeRequestId = null;
1446
+ let latestRun = 0;
1447
+ let pendingRequest = null;
1448
+ const session = {
1449
+ supports: (_snapshot) => true,
1450
+ fork: () => createAiSession(options, onProgress),
1451
+ async run({ snapshot, draft, instruction, signal }) {
1452
+ const run = ++latestRun;
1453
+ activeRequestId = null;
1454
+ retainedIdentity = null;
1455
+ retainedSource = Object.freeze({ snapshot, draft });
1456
+ let resolveRequest;
1457
+ const request = {
1458
+ promise: new Promise((resolve2) => {
1459
+ resolveRequest = resolve2;
1460
+ }),
1461
+ resolve: resolveRequest
1462
+ };
1463
+ pendingRequest = request;
1464
+ try {
1465
+ const result = await adapter.launch({
1466
+ snapshot,
1467
+ draft,
1468
+ instruction,
1469
+ signal,
1470
+ onProgress: (progress) => {
1471
+ if (run !== latestRun) return;
1472
+ onProgress?.(progress);
1473
+ if (!progress.requestId) return;
1474
+ activeRequestId = progress.requestId;
1475
+ request.resolve(progress.requestId);
1476
+ retainedIdentity = Object.freeze({
1477
+ requestId: progress.requestId,
1478
+ conversationId: progress.conversationId,
1479
+ executionId: progress.executionId,
1480
+ snapshotId: snapshot.id,
1481
+ sourceId: draft.sourceId,
1482
+ sourceRevision: draft.sourceRevision,
1483
+ draftRevision: draft.revision
1484
+ });
1485
+ }
1486
+ });
1487
+ if (run === latestRun) {
1488
+ retainedIdentity = result.identity ?? retainedIdentity;
1489
+ activeRequestId = result.identity?.requestId ?? activeRequestId;
1490
+ request.resolve(activeRequestId);
1491
+ }
1492
+ if (result.status !== "completed" || !result.draft)
1493
+ throw new Error(
1494
+ result.message || "AI preparation did not return a draft."
1495
+ );
1496
+ return result.draft;
1497
+ } finally {
1498
+ request.resolve(null);
1499
+ if (run === latestRun && pendingRequest === request) {
1500
+ pendingRequest = null;
1501
+ }
1502
+ }
1503
+ },
1504
+ async recover({ snapshot, draft, signal }) {
1505
+ const recoveryRun = ++latestRun;
1506
+ if (!retainedIdentity)
1507
+ throw new Error(
1508
+ "No recoverable AI preparation exists in this workspace session."
1509
+ );
1510
+ if (!retainedSource || retainedIdentity.snapshotId !== snapshot.id || retainedSource.snapshot.id !== snapshot.id || retainedSource.draft.snapshotId !== draft.snapshotId || retainedSource.draft.sourceId !== draft.sourceId || retainedSource.draft.sourceRevision !== draft.sourceRevision || retainedSource.draft.revision !== draft.revision) {
1511
+ throw new Error(
1512
+ "The recoverable AI preparation belongs to a different source draft."
1513
+ );
1514
+ }
1515
+ const result = await adapter.rejoin(
1516
+ retainedIdentity,
1517
+ retainedSource.draft,
1518
+ (progress) => {
1519
+ if (recoveryRun === latestRun) onProgress?.(progress);
1520
+ },
1521
+ signal
1522
+ );
1523
+ if (recoveryRun !== latestRun)
1524
+ throw new Error("A newer AI preparation started before recovery settled.");
1525
+ retainedIdentity = result.identity ?? retainedIdentity;
1526
+ activeRequestId = retainedIdentity.requestId;
1527
+ if (result.status !== "completed" || !result.draft)
1528
+ throw new Error(
1529
+ result.message || "AI preparation recovery did not return a draft."
1530
+ );
1531
+ return result.draft;
1532
+ },
1533
+ async cancel() {
1534
+ const requestId = activeRequestId ?? (pendingRequest ? await pendingRequest.promise : null);
1535
+ if (!requestId)
1536
+ throw new Error(
1537
+ "The current AI preparation ended before the server returned a request ID; no server cancellation was reported."
1538
+ );
1539
+ await adapter.cancel(requestId);
1540
+ }
1541
+ };
1542
+ return session;
1543
+ }
1544
+ function MatrxContentTransferProvider({
1545
+ children,
1546
+ capabilities,
1547
+ onProgress,
1548
+ ...options
1549
+ }) {
1550
+ const ai = React.useMemo(
1551
+ () => createAiSession(options, onProgress),
1552
+ [
1553
+ options.transport,
1554
+ options.supabase,
1555
+ options.organizationId,
1556
+ options.sourceApp,
1557
+ options.onStreamEvent,
1558
+ options.onRuntimeEvent,
1559
+ onProgress
1560
+ ]
1561
+ );
1562
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_content_transfer2.ContentTransferCapabilitiesProvider, { value: { ...capabilities, ai }, children });
1563
+ }
1564
+ //# sourceMappingURL=index.cjs.map