alran 0.0.0-stage → 0.9.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.
- package/ALRAN_TOOLS_NOTICES.md +64 -0
- package/LICENSE +27 -0
- package/LICENSE-STATUS.md +21 -0
- package/NOTICE +6 -0
- package/README.md +289 -2
- package/THIRD_PARTY_NOTICES.md +113 -0
- package/alran-tools.js +3 -0
- package/assets/agents/_default/prompt-auto_classifier.md +185 -0
- package/assets/agents/_default/prompt-auto_classifier_extras.md +17 -0
- package/assets/agents/_default/prompt-base-all.md +133 -0
- package/assets/agents/_default/prompt-base-all.md.hbs +228 -0
- package/assets/agents/_default/prompt-base-windows.md +5 -0
- package/assets/agents/_default/prompt-base-windows.md.hbs +5 -0
- package/assets/agents/_default/prompt-base-worker.md +10 -0
- package/assets/agents/_default/prompt-base-worker.md.hbs +27 -0
- package/assets/agents/_default/prompt-compact.md +76 -0
- package/assets/agents/_default/prompt-compact_continue.md +9 -0
- package/assets/agents/_default/prompt-git.md +8 -0
- package/assets/agents/_default/prompt-goal.md +13 -0
- package/assets/agents/_default/prompt-session-branch.md +3 -0
- package/assets/agents/_default/prompt-session-branch.md.hbs +30 -0
- package/assets/agents/_default/prompt-session-root.md +3 -0
- package/assets/agents/_default/prompt-session-root.md.hbs +32 -0
- package/assets/agents/_default/prompt-title.md +11 -0
- package/assets/agents/_default/prompt-tool_agent.md +22 -0
- package/assets/agents/_migration/README.md +20 -0
- package/assets/agents/_migration/coder/PERSONA.md +11 -0
- package/assets/agents/_migration/coder/system-prompt.md.hbs +42 -0
- package/assets/agents/_migration/general/PERSONA.md +11 -0
- package/assets/agents/_migration/general/system-prompt.md.hbs +49 -0
- package/assets/agents/_v2/AGENT_CONTEXT.md.hbs +245 -0
- package/assets/agents/_v2/PTC_TOOL_CALLS.md.hbs +35 -0
- package/assets/agents/_v2/coding/SYSTEM.md.hbs +173 -0
- package/assets/agents/_v2/explore.md.hbs +38 -0
- package/assets/agents/_v2/tui/SYSTEM.md.hbs +211 -0
- package/assets/agents/_v2/verifier.md.hbs +32 -0
- package/assets/agents/_v2/work/SYSTEM.md.hbs +186 -0
- package/assets/agents/_v2/worker.md.hbs +27 -0
- package/assets/agents/alran/PERSONA.md +7 -0
- package/assets/agents/alran/features/cron.md.hbs +0 -0
- package/assets/agents/alran/features/delegation.md.hbs +56 -0
- package/assets/agents/alran/features/memory.md.hbs +61 -0
- package/assets/agents/alran/features/recoverable-deletion.md.hbs +10 -0
- package/assets/agents/alran/features/task-management.md.hbs +11 -0
- package/assets/agents/alran/features/web-search.md.hbs +11 -0
- package/assets/agents/alran/modes/coding/online/PERSONA.md.hbs +20 -0
- package/assets/agents/alran/modes/coding/online/SYSTEM.md.hbs +158 -0
- package/assets/agents/alran/modes/work/online/PERSONA.md.hbs +20 -0
- package/assets/agents/alran/modes/work/online/SYSTEM.md.hbs +160 -0
- package/assets/agents/alran/prompt-session-root.md +4 -0
- package/assets/agents/alran/prompt-session-root.md.hbs +4 -0
- package/assets/agents/alran/skills/alran-code-product/SKILL.md +72 -0
- package/assets/agents/alran/skills/alran-code-product/references/account-models.md +61 -0
- package/assets/agents/alran/skills/alran-code-product/references/agents.md +34 -0
- package/assets/agents/alran/skills/alran-code-product/references/extensions.md +46 -0
- package/assets/agents/alran/skills/alran-code-product/references/workflows.md +56 -0
- package/assets/agents/alran/skills/control-in-app-browser/SKILL.md +590 -0
- package/assets/agents/alran/system-prompt.md.hbs +97 -0
- package/assets/agents/builtin-agents.json +1 -0
- package/assets/agents/desktop-task/archive-title/system-en.md +1 -0
- package/assets/agents/desktop-task/checkpoint/system.md +19 -0
- package/assets/agents/desktop-task/output-revision/system.md +1 -0
- package/assets/agents/desktop-task/retry/continuation.md +4 -0
- package/assets/agents/desktop-task/session-title/system.md +41 -0
- package/assets/agents/explore/PERSONA.md +8 -0
- package/assets/agents/explore/agent.md +14 -0
- package/assets/agents/explore/system-prompt.md.hbs +35 -0
- package/assets/agents/greeting.md +61 -0
- package/assets/agents/managed-prompts.json +47 -0
- package/assets/agents/prompt-exemptions.json +36 -0
- package/assets/agents/verifier/PERSONA.md +8 -0
- package/assets/agents/verifier/agent.md +17 -0
- package/assets/agents/verifier/system-prompt.md.hbs +28 -0
- package/assets/agents/worker/PERSONA.md +8 -0
- package/assets/agents/worker/agent.md +18 -0
- package/assets/agents/worker/system-prompt.md.hbs +22 -0
- package/assets/agents/workflow/code-review/review-candidates.md +120 -0
- package/assets/agents/workflow/code-review/reviewer-system.md +75 -0
- package/assets/agents/workflow/goal/budget-limit.md +16 -0
- package/assets/agents/workflow/goal/continuation.md +62 -0
- package/assets/agents/workflow/goal/objective-updated.md +16 -0
- package/assets/agents/workflow/goal/recovery-terminal-audit.md +13 -0
- package/assets/agents/workflow/goal/recovery.md +11 -0
- package/assets/agents/workflow/goal/terminal-audit.md +10 -0
- package/assets/agents/workflow/plan-mode/agent-entry.md +72 -0
- package/assets/agents/workflow/prompt-hook/system.md +0 -0
- package/assets/models-dev-catalog.json.gz +0 -0
- package/assets/prompts/code-review/review-candidates.md +120 -0
- package/assets/prompts/code-review/reviewer-system.md +75 -0
- package/assets/skills/alran-tools-master/SKILL.md +127 -0
- package/assets/skills/code-review/SKILL.md +51 -0
- package/assets/skills/cu-desktop/SKILL.md +255 -0
- package/assets/skills/deep-research/SKILL.md +30 -0
- package/assets/skills/deploy-website/SKILL.md +52 -0
- package/assets/skills/docx/LICENSE +21 -0
- package/assets/skills/docx/SKILL.md +259 -0
- package/assets/skills/docx/assets/styles/academic_styles.xml +250 -0
- package/assets/skills/docx/assets/styles/corporate_styles.xml +284 -0
- package/assets/skills/docx/assets/styles/default_styles.xml +449 -0
- package/assets/skills/docx/assets/xsd/aesthetic-rules.xsd +470 -0
- package/assets/skills/docx/assets/xsd/business-rules.xsd +130 -0
- package/assets/skills/docx/assets/xsd/common-types.xsd +159 -0
- package/assets/skills/docx/assets/xsd/wml-subset.xsd +589 -0
- package/assets/skills/docx/docs/acceptance-checklists/create.md +7 -0
- package/assets/skills/docx/docs/acceptance-checklists/edit.md +6 -0
- package/assets/skills/docx/docs/acceptance-checklists/layout-repair.md +7 -0
- package/assets/skills/docx/docs/acceptance-checklists/template.md +6 -0
- package/assets/skills/docx/docs/acceptance.md +139 -0
- package/assets/skills/docx/docs/anti-patterns.md +14 -0
- package/assets/skills/docx/docs/backends.md +116 -0
- package/assets/skills/docx/docs/evidence.md +73 -0
- package/assets/skills/docx/docs/failure-taxonomy.md +71 -0
- package/assets/skills/docx/docs/index.md +50 -0
- package/assets/skills/docx/docs/rendered-delivery.md +125 -0
- package/assets/skills/docx/docs/router.md +122 -0
- package/assets/skills/docx/docs/tables-and-numbering.md +27 -0
- package/assets/skills/docx/docs/task-apply-template.md +141 -0
- package/assets/skills/docx/docs/task-compare-two-docx.md +48 -0
- package/assets/skills/docx/docs/task-create.md +124 -0
- package/assets/skills/docx/docs/task-edit-fill.md +69 -0
- package/assets/skills/docx/docs/task-read-content.md +148 -0
- package/assets/skills/docx/docs/task-read-rendered.md +78 -0
- package/assets/skills/docx/docs/task-read-structure.md +93 -0
- package/assets/skills/docx/docs/task-repair-layout.md +70 -0
- package/assets/skills/docx/docs/template-dsl.md +32 -0
- package/assets/skills/docx/docs/track-changes.md +15 -0
- package/assets/skills/docx/docs/xml-patch-dsl.md +33 -0
- package/assets/skills/docx/references/cjk_typography.md +357 -0
- package/assets/skills/docx/references/cjk_university_template_guide.md +184 -0
- package/assets/skills/docx/references/comments_guide.md +191 -0
- package/assets/skills/docx/references/design_good_bad_examples.md +829 -0
- package/assets/skills/docx/references/design_principles.md +819 -0
- package/assets/skills/docx/references/openxml_element_order.md +308 -0
- package/assets/skills/docx/references/openxml_encyclopedia_part1.md +4061 -0
- package/assets/skills/docx/references/openxml_encyclopedia_part2.md +2820 -0
- package/assets/skills/docx/references/openxml_encyclopedia_part3.md +3381 -0
- package/assets/skills/docx/references/openxml_namespaces.md +82 -0
- package/assets/skills/docx/references/openxml_units.md +72 -0
- package/assets/skills/docx/references/sample-patch-plans.json +22 -0
- package/assets/skills/docx/references/sample-task-intents.json +5 -0
- package/assets/skills/docx/references/sample-template-manifests.json +21 -0
- package/assets/skills/docx/references/scenario_a_create.md +284 -0
- package/assets/skills/docx/references/scenario_b_edit_content.md +295 -0
- package/assets/skills/docx/references/scenario_c_apply_template.md +456 -0
- package/assets/skills/docx/references/track_changes_guide.md +200 -0
- package/assets/skills/docx/references/troubleshooting.md +506 -0
- package/assets/skills/docx/references/typography_guide.md +294 -0
- package/assets/skills/docx/references/xsd_validation_guide.md +158 -0
- package/assets/skills/docx/scripts/build_patch_plan.py +29 -0
- package/assets/skills/docx/scripts/diff_docx_structure.py +61 -0
- package/assets/skills/docx/scripts/doc_to_docx.ps1 +85 -0
- package/assets/skills/docx/scripts/doc_to_docx.sh +40 -0
- package/assets/skills/docx/scripts/docx_preview.ps1 +76 -0
- package/assets/skills/docx/scripts/docx_preview.sh +37 -0
- package/assets/skills/docx/scripts/docx_to_pdf.py +87 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Cli/AlranAIDocx.Cli.csproj +19 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Cli/Program.cs +18 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/AlranAIDocx.Core.csproj +15 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/AnalyzeCommand.cs +147 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/ApplyTemplateCommand.cs +322 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/CreateCommand.cs +324 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/DiffCommand.cs +155 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/EditContentCommand.cs +487 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/FixOrderCommand.cs +108 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/MergeRunsCommand.cs +122 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/ValidateCommand.cs +107 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/CommentSynchronizer.cs +169 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/ElementOrder.cs +80 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/NamespaceConstants.cs +42 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/RunMerger.cs +81 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/StyleAnalyzer.cs +81 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/TrackChangesHelper.cs +99 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/UnitConverter.cs +23 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples.cs +1832 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch1.cs +910 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch2.cs +999 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch3.cs +1048 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch4.cs +1038 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/CharacterFormattingSamples.cs +1020 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/DocumentCreationSamples.cs +1121 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/FieldAndTocSamples.cs +624 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/FootnoteAndCommentSamples.cs +675 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/HeaderFooterSamples.cs +838 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ImageSamples.cs +917 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ListAndNumberingSamples.cs +826 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ParagraphFormattingSamples.cs +1199 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/StyleSystemSamples.cs +1487 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/TableSamples.cs +1163 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/TrackChangesSamples.cs +595 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/CjkHelper.cs +39 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/FontDefaults.cs +24 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/PageSizes.cs +20 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/BusinessRuleValidator.cs +224 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/GateCheckValidator.cs +148 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/ValidationResult.cs +23 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/XsdValidator.cs +69 -0
- package/assets/skills/docx/scripts/dotnet/AlranAIDocx.slnx +4 -0
- package/assets/skills/docx/scripts/env_check.ps1 +327 -0
- package/assets/skills/docx/scripts/env_check.sh +340 -0
- package/assets/skills/docx/scripts/extract_docx_text.py +1075 -0
- package/assets/skills/docx/scripts/pack_docx.py +31 -0
- package/assets/skills/docx/scripts/read_docx_structure.py +1032 -0
- package/assets/skills/docx/scripts/render_docx_pages.py +147 -0
- package/assets/skills/docx/scripts/rendered_report.py +609 -0
- package/assets/skills/docx/scripts/setup.ps1 +542 -0
- package/assets/skills/docx/scripts/setup.sh +537 -0
- package/assets/skills/docx/scripts/unpack_docx.py +29 -0
- package/assets/skills/docx/scripts/validate_template_manifest.py +60 -0
- package/assets/skills/docx/scripts/verify_anchor_atomicity.py +87 -0
- package/assets/skills/edit-deployed-website/SKILL.md +27 -0
- package/assets/skills/init/SKILL.md +135 -0
- package/assets/skills/llm-call/SKILL.md +48 -0
- package/assets/skills/llm-call/scripts/llm_call.py +458 -0
- package/assets/skills/pdf/SKILL.md +280 -0
- package/assets/skills/pdf/docs/advanced-reference.md +711 -0
- package/assets/skills/pdf/docs/create-guide.md +437 -0
- package/assets/skills/pdf/docs/design-guide.md +204 -0
- package/assets/skills/pdf/docs/forms-guide.md +462 -0
- package/assets/skills/pdf/docs/html-pdf-spec.md +500 -0
- package/assets/skills/pdf/docs/latex-academic-thesis-guide.md +233 -0
- package/assets/skills/pdf/docs/latex-technical-book-guide.md +112 -0
- package/assets/skills/pdf/docs/pitfalls-index.md +792 -0
- package/assets/skills/pdf/docs/read-guide.md +358 -0
- package/assets/skills/pdf/docs/reformat-guide.md +238 -0
- package/assets/skills/pdf/docs/skill-readme-archive.md +151 -0
- package/assets/skills/pdf/docs/troubleshooting.md +86 -0
- package/assets/skills/pdf/docs/vision-guide.md +188 -0
- package/assets/skills/pdf/scripts/__init__.py +0 -0
- package/assets/skills/pdf/scripts/_pdf_read_lib.py +284 -0
- package/assets/skills/pdf/scripts/fill/__init__.py +0 -0
- package/assets/skills/pdf/scripts/fill/acroform_apply.py +153 -0
- package/assets/skills/pdf/scripts/fill/overlay_apply.py +109 -0
- package/assets/skills/pdf/scripts/lib/__init__.py +0 -0
- package/assets/skills/pdf/scripts/lib/acroform_io.py +170 -0
- package/assets/skills/pdf/scripts/lib/cli_utils.py +41 -0
- package/assets/skills/pdf/scripts/lib/geometry.py +79 -0
- package/assets/skills/pdf/scripts/make.sh +388 -0
- package/assets/skills/pdf/scripts/merge.py +112 -0
- package/assets/skills/pdf/scripts/pdf_inspect/__init__.py +0 -0
- package/assets/skills/pdf/scripts/pdf_inspect/acroform_inspect.py +52 -0
- package/assets/skills/pdf/scripts/pdf_inspect/acroform_probe.py +57 -0
- package/assets/skills/pdf/scripts/pdf_inspect/layout_scan.py +164 -0
- package/assets/skills/pdf/scripts/read_pdf_vision.py +473 -0
- package/assets/skills/pdf/scripts/reformat_parse.py +181 -0
- package/assets/skills/pdf/scripts/render/__init__.py +0 -0
- package/assets/skills/pdf/scripts/render/overlay_preview.py +86 -0
- package/assets/skills/pdf/scripts/render/page_rasterize.py +85 -0
- package/assets/skills/pdf/scripts/render_html.cjs +205 -0
- package/assets/skills/pdf/scripts/validate/__init__.py +0 -0
- package/assets/skills/pdf/scripts/validate/geometry_lint.py +124 -0
- package/assets/skills/pdf/templates/INDEX.md +90 -0
- package/assets/skills/pdf/templates/bilingual-menu-premium/README.md +175 -0
- package/assets/skills/pdf/templates/bilingual-menu-premium/skeleton.html +343 -0
- package/assets/skills/pdf/templates/brand-guide-2page/README.md +140 -0
- package/assets/skills/pdf/templates/brand-guide-2page/skeleton.html +264 -0
- package/assets/skills/pdf/templates/data-viz-report/README.md +234 -0
- package/assets/skills/pdf/templates/data-viz-report/skeleton.html +835 -0
- package/assets/skills/pdf/templates/form-fill-acroform/README.md +195 -0
- package/assets/skills/pdf/templates/form-fill-acroform/field_values.template.json +118 -0
- package/assets/skills/pdf/templates/latex-academic-thesis/README.md +146 -0
- package/assets/skills/pdf/templates/latex-academic-thesis/source.tex +334 -0
- package/assets/skills/pdf/templates/latex-technical-book/README.md +130 -0
- package/assets/skills/pdf/templates/latex-technical-book/README.template-source.md +62 -0
- package/assets/skills/pdf/templates/latex-technical-book/source.tex +439 -0
- package/assets/skills/pdf/templates/multi-article-aggregator/README.md +148 -0
- package/assets/skills/pdf/templates/multi-article-aggregator/pipeline.md +223 -0
- package/assets/skills/pdf/templates/multilang-research-report/README.md +136 -0
- package/assets/skills/pdf/templates/multilang-research-report/skeleton.html +242 -0
- package/assets/skills/pdf/templates/reformat-default/README.md +136 -0
- package/assets/skills/pdf/templates/reformat-default/skeleton.html +204 -0
- package/assets/skills/pdf/templates/translate-preserve-layout/README.md +136 -0
- package/assets/skills/pdf/templates/translate-preserve-layout/skeleton.html +96 -0
- package/assets/skills/pdf/templates/translate-preserve-layout/terminology.template.json +66 -0
- package/assets/skills/pptx/SKILL.md +283 -0
- package/assets/skills/pptx/references/design-system.md +424 -0
- package/assets/skills/pptx/references/editing.md +162 -0
- package/assets/skills/pptx/references/element-map.md +229 -0
- package/assets/skills/pptx/references/pitfalls.md +205 -0
- package/assets/skills/pptx/references/pptxgenjs.md +420 -0
- package/assets/skills/pptx/references/preview-selection-writeback.md +65 -0
- package/assets/skills/pptx/references/python-pptx-recipes.md +63 -0
- package/assets/skills/pptx/references/slide-types.md +413 -0
- package/assets/skills/pptx/scripts/alran-ppt-map.cjs +280 -0
- package/assets/skills/pptx/scripts/audit_pptx.py +708 -0
- package/assets/skills/pptx/scripts/extract_comments.py +468 -0
- package/assets/skills/pptx/scripts/extract_images.py +226 -0
- package/assets/skills/pptx/scripts/extract_pptx.py +285 -0
- package/assets/skills/pptx/scripts/pdf2png.swift +203 -0
- package/assets/skills/pptx/scripts/pptx-screenshot.sh +105 -0
- package/assets/skills/resume-codex/SKILL.md +53 -0
- package/assets/skills/resume-codex/scripts/session-reader.mjs +445 -0
- package/assets/skills/skill-creator/SKILL.md +188 -0
- package/assets/skills/skill-creator/references/anti-patterns.md +149 -0
- package/assets/skills/skill-creator/references/commands-macos-linux.md +38 -0
- package/assets/skills/skill-creator/references/commands-windows-powershell.md +48 -0
- package/assets/skills/skill-creator/references/description-rubric.md +83 -0
- package/assets/skills/skill-creator/references/skill-template.md +101 -0
- package/assets/skills/skill-creator/references/when-to-bundle-scripts.md +139 -0
- package/assets/skills/skill-creator/scripts/lint-skill.js +226 -0
- package/assets/skills/skill-refiner/SKILL.md +137 -0
- package/assets/skills/visual-page/SKILL.md +194 -0
- package/assets/skills/x-link-reader/SKILL.md +108 -0
- package/assets/skills/xlsx/SKILL.md +498 -0
- package/assets/skills/xlsx/docs/advanced-reference.md +410 -0
- package/assets/skills/xlsx/docs/conventions-guide.md +217 -0
- package/assets/skills/xlsx/docs/create-edit-guide.md +410 -0
- package/assets/skills/xlsx/docs/pitfalls-index.md +759 -0
- package/assets/skills/xlsx/docs/raw-xml-escape-hatch.md +201 -0
- package/assets/skills/xlsx/docs/recalc-guide.md +295 -0
- package/assets/skills/xlsx/scripts/office/helpers/__init__.py +0 -0
- package/assets/skills/xlsx/scripts/office/helpers/merge_runs.py +199 -0
- package/assets/skills/xlsx/scripts/office/helpers/simplify_redlines.py +197 -0
- package/assets/skills/xlsx/scripts/office/pack.py +159 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
- package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
- package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
- package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
- package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
- package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
- package/assets/skills/xlsx/scripts/office/schemas/mce/mc.xsd +75 -0
- package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
- package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
- package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
- package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
- package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
- package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
- package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
- package/assets/skills/xlsx/scripts/office/soffice.py +191 -0
- package/assets/skills/xlsx/scripts/office/unpack.py +132 -0
- package/assets/skills/xlsx/scripts/office/validate.py +117 -0
- package/assets/skills/xlsx/scripts/office/validators/__init__.py +15 -0
- package/assets/skills/xlsx/scripts/office/validators/base.py +851 -0
- package/assets/skills/xlsx/scripts/office/validators/docx.py +446 -0
- package/assets/skills/xlsx/scripts/office/validators/pptx.py +275 -0
- package/assets/skills/xlsx/scripts/office/validators/redlining.py +247 -0
- package/assets/skills/xlsx/scripts/recalc.py +450 -0
- package/chunks/account-commands-JZ6NXTTK.js +2 -0
- package/chunks/anthropic-MN33DP4E.js +2 -0
- package/chunks/application-ITGAJ4HC.js +2 -0
- package/chunks/auth-command-V3RVPLZO.js +2 -0
- package/chunks/azure-openai-responses-OWHMUNKC.js +2 -0
- package/chunks/chunk-2TF6JAQM.js +2 -0
- package/chunks/chunk-33CNY6GP.js +2 -0
- package/chunks/chunk-3AODGLMF.js +2 -0
- package/chunks/chunk-44VPC5LA.js +38 -0
- package/chunks/chunk-4CN3IJFH.js +2 -0
- package/chunks/chunk-4PDIO3M6.js +2 -0
- package/chunks/chunk-4X22UJQH.js +164 -0
- package/chunks/chunk-6255CZPL.js +2 -0
- package/chunks/chunk-6P4UKHGR.js +2 -0
- package/chunks/chunk-7QLAXRD2.js +1085 -0
- package/chunks/chunk-7XYOYZX2.js +2 -0
- package/chunks/chunk-A7GMJNA2.js +29 -0
- package/chunks/chunk-AGUSPIUP.js +2 -0
- package/chunks/chunk-BQ3CF3KE.js +2 -0
- package/chunks/chunk-C3CMJAAV.js +3 -0
- package/chunks/chunk-CJM7ZJ6W.js +7 -0
- package/chunks/chunk-CSOUJVKM.js +2 -0
- package/chunks/chunk-D66ZSHXR.js +2 -0
- package/chunks/chunk-D7MGU75P.js +2 -0
- package/chunks/chunk-E3GLGDGC.js +5 -0
- package/chunks/chunk-ENHOPPS7.js +16 -0
- package/chunks/chunk-EOR6EDNR.js +2 -0
- package/chunks/chunk-EYK25HWR.js +2 -0
- package/chunks/chunk-F46IELF5.js +2 -0
- package/chunks/chunk-FC4M2B7E.js +2 -0
- package/chunks/chunk-FSNYOJPJ.js +2 -0
- package/chunks/chunk-FUERW2DW.js +3 -0
- package/chunks/chunk-FXOH6TEQ.js +21 -0
- package/chunks/chunk-GP52JZMY.js +2 -0
- package/chunks/chunk-GRXX6I72.js +2 -0
- package/chunks/chunk-GSYHBK5Q.js +6 -0
- package/chunks/chunk-HNWBFJNO.js +2 -0
- package/chunks/chunk-IIE366LR.js +6706 -0
- package/chunks/chunk-IWK7PZP7.js +207 -0
- package/chunks/chunk-J3KCPYZT.js +2 -0
- package/chunks/chunk-KCLRJQ53.js +59 -0
- package/chunks/chunk-LU4RPLJ3.js +2 -0
- package/chunks/chunk-LZJYNT32.js +2 -0
- package/chunks/chunk-M7GW4VMR.js +27 -0
- package/chunks/chunk-MACBL5HF.js +2 -0
- package/chunks/chunk-N5NTXCJI.js +2 -0
- package/chunks/chunk-N5SVBCUB.js +7 -0
- package/chunks/chunk-N6W7ZL26.js +2 -0
- package/chunks/chunk-NWB7LFOK.js +131 -0
- package/chunks/chunk-OIQ336YE.js +16 -0
- package/chunks/chunk-OQNU3VPS.js +30 -0
- package/chunks/chunk-OTDNOWXG.js +16 -0
- package/chunks/chunk-PNXZWSWT.js +3 -0
- package/chunks/chunk-QFUV5PX6.js +2 -0
- package/chunks/chunk-QIN5ZBE2.js +2 -0
- package/chunks/chunk-QKBN5CGI.js +2 -0
- package/chunks/chunk-QPGTKSIQ.js +2 -0
- package/chunks/chunk-SIOLUFGG.js +2 -0
- package/chunks/chunk-TW23QKAD.js +3 -0
- package/chunks/chunk-U3RMPDXU.js +2 -0
- package/chunks/chunk-U7U3DJHF.js +2 -0
- package/chunks/chunk-VLXX22YO.js +2 -0
- package/chunks/chunk-WHD2XVT2.js +2 -0
- package/chunks/chunk-WTAJMYF2.js +249 -0
- package/chunks/chunk-WWNUAU4P.js +29 -0
- package/chunks/chunk-WYANV3IX.js +4 -0
- package/chunks/chunk-XAGZ6ZEU.js +9 -0
- package/chunks/chunk-XFCC2CI2.js +24 -0
- package/chunks/chunk-XQK7JM66.js +2 -0
- package/chunks/chunk-YLQXZBEL.js +2 -0
- package/chunks/chunk-YPV2X2RG.js +2 -0
- package/chunks/chunk-Z6BHCXKT.js +25 -0
- package/chunks/chunk-Z6HBNJCA.js +8 -0
- package/chunks/chunk-ZQKVUPKA.js +2 -0
- package/chunks/chunk-ZQOALVGL.js +2 -0
- package/chunks/clipboard-image-PQPC4EHR.js +2 -0
- package/chunks/data-dir-LDVKDCJ2.js +2 -0
- package/chunks/dist-2BRD4JFU.js +11 -0
- package/chunks/dist-EXKHRFQO.js +5 -0
- package/chunks/emscripten-module-RD6P2XH5.js +2 -0
- package/chunks/emscripten-module-WYNDFH3N.js +2 -0
- package/chunks/emscripten-module-XPTEOIWW.js +2 -0
- package/chunks/emscripten-module-ZS3PMSDF.js +2 -0
- package/chunks/ffi-IO7WZQNG.js +2 -0
- package/chunks/ffi-M5UP5J6C.js +2 -0
- package/chunks/ffi-ORLOPBB3.js +2 -0
- package/chunks/ffi-OUPK6AY6.js +2 -0
- package/chunks/google-UJAPMFAB.js +2 -0
- package/chunks/google-vertex-VLSF55PW.js +2 -0
- package/chunks/install-source-JTIUC4G4.js +2 -0
- package/chunks/launcher-FCZ3EDBF.js +61 -0
- package/chunks/lifecycle-GY435YMF.js +2 -0
- package/chunks/main-TQGGRHTS.js +13 -0
- package/chunks/mistral-ZJZUEF2X.js +3 -0
- package/chunks/module-6F3E5H7Y-BN7QWGYB.js +2 -0
- package/chunks/module-asyncify-R6PWJ6ZV-P4FWSBAY.js +2 -0
- package/chunks/multipart-parser-L6M455MS.js +2 -0
- package/chunks/network-proxy-U72JCK2I.js +2 -0
- package/chunks/openai-codex-responses-FPCDNRL5.js +2 -0
- package/chunks/openai-completions-D32YW6KL.js +2 -0
- package/chunks/openai-responses-ZCGSENM4.js +2 -0
- package/chunks/openrouter-G2EHY5BD.js +2 -0
- package/chunks/otel-OHXIZ666.js +2 -0
- package/chunks/package-contract-GVXTMJ3N.js +2 -0
- package/chunks/pdfjs-SHZAF7PF.js +107 -0
- package/chunks/photon_rs-C52RL4CI.js +3 -0
- package/chunks/plugin-command-OSAFHS7C.js +2 -0
- package/chunks/provider-command-SKTCHD4E.js +2 -0
- package/chunks/questionnaire-bridge-ISQOCYWY.js +2 -0
- package/chunks/run-acp-command-SG2BDMFJ.js +2 -0
- package/chunks/run-exec-command-5ADSQR2Z.js +15 -0
- package/chunks/skills-command-XXXEZAG6.js +2 -0
- package/chunks/src-DNIDEMVV.js +2 -0
- package/chunks/src-IBHIRTD7.js +2 -0
- package/chunks/telemetry-J7ZLGF5X.js +2 -0
- package/chunks/telemetry-command-COQG2AKK.js +5 -0
- package/chunks/tools-WDBB2JKV.js +2 -0
- package/chunks/undici-TUGHZJSA.js +2 -0
- package/chunks/update-NB6OD572.js +14 -0
- package/chunks/update-hint-ED7O67WU.js +3 -0
- package/chunks/wechat-onboard-UWXQW2HT.js +2 -0
- package/cli.js +5 -0
- package/configs/data-minimal.yaml +50 -0
- package/embedded/alran-tools/cli.mjs +4961 -0
- package/embedded/alran-tools/manifest.json +25 -0
- package/emscripten-module.wasm +0 -0
- package/image-preview-worker.js +2 -0
- package/internal-bin/alran-tools +9 -0
- package/internal-bin/alran-tools.cmd +8 -0
- package/matrix-mcp-stdio.js +4 -0
- package/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
- package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
- package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
- package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
- package/package.json +38 -4
- package/photon_rs_bg.wasm +0 -0
- package/quickjs-worker.js +152 -0
- package/vendor/java-proxy-agent/build.ts +97 -0
- package/vendor/java-proxy-agent/srt-proxy-agent.jar +0 -0
- package/vendor/seccomp/arm64/apply-seccomp +0 -0
- package/vendor/seccomp/build.ts +74 -0
- package/vendor/seccomp/x64/apply-seccomp +0 -0
- package/vendor/srt-win/arm64/srt-win.exe +0 -0
- package/vendor/srt-win/build.ts +40 -0
- package/vendor/srt-win/x64/srt-win.exe +0 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
"""xlsx formula recalculation using LibreOffice and openpyxl, returning a JSON error list.
|
|
2
|
+
|
|
3
|
+
Part of the Alran xlsx skill (MIT). See LICENSE for terms.
|
|
4
|
+
|
|
5
|
+
The CLI retains the upstream contract:
|
|
6
|
+
|
|
7
|
+
python scripts/recalc.py <workbook> [timeout_seconds]
|
|
8
|
+
|
|
9
|
+
JSON output fields are fixed: ``status`` / ``total_errors`` / ``total_formulas`` /
|
|
10
|
+
``error_summary``; the error path returns only ``{"error": "..."}``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import platform
|
|
19
|
+
import signal
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from office.soffice import get_soffice_env
|
|
25
|
+
from openpyxl import load_workbook
|
|
26
|
+
|
|
27
|
+
# --- LibreOffice Basic module storage locations -------------------------------
|
|
28
|
+
BASIC_DIR_DARWIN = "~/Library/Application Support/LibreOffice/4/user/basic/Standard"
|
|
29
|
+
BASIC_DIR_LINUX = "~/.config/libreoffice/4/user/basic/Standard"
|
|
30
|
+
BASIC_MODULE_FILE = "Module1.xba"
|
|
31
|
+
|
|
32
|
+
# Note: Keep macro content and XML identical to upstream, or LibreOffice cannot find RecalculateAndSave.
|
|
33
|
+
LO_RECALC_BASIC = """<?xml version="1.0" encoding="UTF-8"?>
|
|
34
|
+
<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
|
|
35
|
+
<script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
|
|
36
|
+
Sub RecalculateAndSave()
|
|
37
|
+
ThisComponent.calculateAll()
|
|
38
|
+
ThisComponent.store()
|
|
39
|
+
ThisComponent.close(True)
|
|
40
|
+
End Sub
|
|
41
|
+
</script:module>"""
|
|
42
|
+
|
|
43
|
+
# List the seven common Excel error markers alphabetically, matching SKILL.md.
|
|
44
|
+
XLSX_ERROR_TOKENS = (
|
|
45
|
+
"#DIV/0!",
|
|
46
|
+
"#N/A",
|
|
47
|
+
"#NAME?",
|
|
48
|
+
"#NULL!",
|
|
49
|
+
"#NUM!",
|
|
50
|
+
"#REF!",
|
|
51
|
+
"#VALUE!",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
_BASIC_INVOCATION = (
|
|
55
|
+
"vnd.sun.star.script:Standard.Module1.RecalculateAndSave"
|
|
56
|
+
"?language=Basic&location=application"
|
|
57
|
+
)
|
|
58
|
+
_MAX_LOCATIONS_PER_TOKEN = 20
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _openpyxl_compat_hint(exc: Exception | str) -> str:
|
|
62
|
+
"""Return a user-facing hint for known openpyxl compatibility failures."""
|
|
63
|
+
msg = str(exc)
|
|
64
|
+
low = msg.lower()
|
|
65
|
+
if "expected <class 'int'>" in msg or "merge" in low or "merged" in low:
|
|
66
|
+
return (
|
|
67
|
+
"openpyxl failed while parsing merged-cell metadata after LibreOffice "
|
|
68
|
+
"saved the workbook. This is a known non-standard/rewritten mergeCell "
|
|
69
|
+
"compatibility issue; recalc.py will use raw XML scanning, so do not "
|
|
70
|
+
"retry blindly. If you need to read values later, use "
|
|
71
|
+
"load_workbook(..., read_only=True, data_only=True) or raw XML."
|
|
72
|
+
)
|
|
73
|
+
if "chart" in low or "drawing" in low or "graphic" in low:
|
|
74
|
+
return (
|
|
75
|
+
"openpyxl failed while parsing chart/drawing metadata. Formula/error "
|
|
76
|
+
"verification does not need chart objects, so recalc.py will bypass "
|
|
77
|
+
"openpyxl and scan worksheet XML directly. Do not retry unless the "
|
|
78
|
+
"raw-XML fallback also fails."
|
|
79
|
+
)
|
|
80
|
+
if "stylesheet" in low or "style" in low or "numberformat" in low:
|
|
81
|
+
return (
|
|
82
|
+
"openpyxl failed while parsing styles/number formats. Formula/error "
|
|
83
|
+
"verification can continue via raw worksheet XML, but downstream code "
|
|
84
|
+
"should avoid rewriting this workbook with openpyxl unless style "
|
|
85
|
+
"round-trip has been tested."
|
|
86
|
+
)
|
|
87
|
+
return (
|
|
88
|
+
"openpyxl could not parse this workbook, likely due to non-standard XLSX "
|
|
89
|
+
"metadata. recalc.py will try a raw-XML scan that ignores charts, drawings, "
|
|
90
|
+
"styles, and merged-cell objects and only verifies worksheet formulas/errors."
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# --- subprocess helpers ------------------------------------------------------
|
|
95
|
+
def has_coreutils_timeout() -> bool:
|
|
96
|
+
"""Use coreutils' ``gtimeout`` on macOS and the built-in ``timeout`` on Linux."""
|
|
97
|
+
try:
|
|
98
|
+
subprocess.run(
|
|
99
|
+
["gtimeout", "--version"],
|
|
100
|
+
capture_output=True,
|
|
101
|
+
timeout=1,
|
|
102
|
+
check=False,
|
|
103
|
+
)
|
|
104
|
+
return True
|
|
105
|
+
except (FileNotFoundError, subprocess.TimeoutExpired):
|
|
106
|
+
return False
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _wrap_with_timeout(cmd: list[str], timeout_sec: int) -> list[str]:
|
|
110
|
+
sysname = platform.system()
|
|
111
|
+
if sysname == "Linux":
|
|
112
|
+
return ["timeout", str(timeout_sec), *cmd]
|
|
113
|
+
if sysname == "Darwin" and has_coreutils_timeout():
|
|
114
|
+
return ["gtimeout", str(timeout_sec), *cmd]
|
|
115
|
+
return cmd
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _build_soffice_cmdline(workbook_path: str) -> list[str]:
|
|
119
|
+
return [
|
|
120
|
+
"soffice",
|
|
121
|
+
"--headless",
|
|
122
|
+
"--norestore",
|
|
123
|
+
_BASIC_INVOCATION,
|
|
124
|
+
workbook_path,
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# --- LibreOffice Basic bootstrap --------------------------------------------
|
|
129
|
+
def install_recalc_basic() -> bool:
|
|
130
|
+
"""Idempotently write the RecalculateAndSave macro to the LibreOffice user profile."""
|
|
131
|
+
sysname = platform.system()
|
|
132
|
+
basic_dir = os.path.expanduser(
|
|
133
|
+
BASIC_DIR_DARWIN if sysname == "Darwin" else BASIC_DIR_LINUX
|
|
134
|
+
)
|
|
135
|
+
module_path = Path(basic_dir) / BASIC_MODULE_FILE
|
|
136
|
+
|
|
137
|
+
# Already written and still contains the target Sub: consider it ready.
|
|
138
|
+
if module_path.exists() and "RecalculateAndSave" in module_path.read_text():
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
# If the user profile does not exist, cold-start soffice once to create its directories.
|
|
142
|
+
if not module_path.parent.exists():
|
|
143
|
+
subprocess.run(
|
|
144
|
+
["soffice", "--headless", "--terminate_after_init"],
|
|
145
|
+
capture_output=True,
|
|
146
|
+
timeout=10,
|
|
147
|
+
env=get_soffice_env(),
|
|
148
|
+
)
|
|
149
|
+
module_path.parent.mkdir(parents=True, exist_ok=True)
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
module_path.write_text(LO_RECALC_BASIC)
|
|
153
|
+
return True
|
|
154
|
+
except Exception:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# --- Main flow ---------------------------------------------------------------
|
|
159
|
+
def recalculate_workbook(
|
|
160
|
+
workbook_path: str | os.PathLike,
|
|
161
|
+
*,
|
|
162
|
+
timeout_sec: int = 30,
|
|
163
|
+
) -> dict:
|
|
164
|
+
"""Recalculate all workbook formulas and return a JSON dictionary matching the upstream schema."""
|
|
165
|
+
target = Path(workbook_path)
|
|
166
|
+
if not target.exists():
|
|
167
|
+
return {"error": f"workbook 不存在:{target}"}
|
|
168
|
+
|
|
169
|
+
abs_path = str(target.resolve())
|
|
170
|
+
|
|
171
|
+
if not install_recalc_basic():
|
|
172
|
+
return {"error": "无法写入 LibreOffice Basic 回算模块"}
|
|
173
|
+
|
|
174
|
+
cmd = _wrap_with_timeout(_build_soffice_cmdline(abs_path), timeout_sec)
|
|
175
|
+
# Popen + start_new_session so the Python-side timeout fallback can
|
|
176
|
+
# kill the whole process group. Without it, only the wrapper dies and
|
|
177
|
+
# the LibreOffice child keeps the single-instance profile lock,
|
|
178
|
+
# silently breaking every subsequent invocation.
|
|
179
|
+
proc = subprocess.Popen(
|
|
180
|
+
cmd,
|
|
181
|
+
stdout=subprocess.PIPE,
|
|
182
|
+
stderr=subprocess.PIPE,
|
|
183
|
+
text=True,
|
|
184
|
+
env=get_soffice_env(),
|
|
185
|
+
start_new_session=True,
|
|
186
|
+
)
|
|
187
|
+
try:
|
|
188
|
+
_stdout, stderr_text = proc.communicate(timeout=timeout_sec + 5)
|
|
189
|
+
except subprocess.TimeoutExpired:
|
|
190
|
+
try:
|
|
191
|
+
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
|
192
|
+
except (ProcessLookupError, PermissionError):
|
|
193
|
+
proc.kill()
|
|
194
|
+
proc.wait()
|
|
195
|
+
return {
|
|
196
|
+
"error": (
|
|
197
|
+
f"soffice exceeded {timeout_sec}s timeout; killed entire "
|
|
198
|
+
"process group via Python-side fallback. On macOS install "
|
|
199
|
+
"coreutils (`brew install coreutils`) so the gtimeout "
|
|
200
|
+
"wrapper can cap soffice cleanly."
|
|
201
|
+
)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
# 124 is timeout's exit code; the document is already saved, so error scanning may continue.
|
|
205
|
+
if proc.returncode not in (0, 124):
|
|
206
|
+
stderr_text = stderr_text or "Unknown error during recalculation"
|
|
207
|
+
if "Module1" in stderr_text or "RecalculateAndSave" not in stderr_text:
|
|
208
|
+
return {"error": "LibreOffice Basic 模块未正确加载"}
|
|
209
|
+
return {"error": stderr_text}
|
|
210
|
+
|
|
211
|
+
# LibreOffice succeeded; openpyxl may still choke on rewritten merged
|
|
212
|
+
# cells. Try the openpyxl path first, fall back to a raw-XML scan that
|
|
213
|
+
# bypasses merged-cell parsing entirely.
|
|
214
|
+
try:
|
|
215
|
+
return _scan_for_errors(target)
|
|
216
|
+
except Exception as exc:
|
|
217
|
+
# openpyxl is strict about the full workbook package (merged cells,
|
|
218
|
+
# chart drawings, styles, relationship targets). Recalc verification only
|
|
219
|
+
# needs worksheet cached values and <f> formula nodes, so fall back to a
|
|
220
|
+
# raw-XML scan for ANY openpyxl parse failure instead of crashing or
|
|
221
|
+
# encouraging blind retries.
|
|
222
|
+
try:
|
|
223
|
+
return _scan_for_errors_via_xml(target, exc)
|
|
224
|
+
except Exception as fallback_exc:
|
|
225
|
+
return {
|
|
226
|
+
"error": (
|
|
227
|
+
"LibreOffice recalc completed, but workbook verification failed. "
|
|
228
|
+
f"openpyxl_error={type(exc).__name__}: {exc}; "
|
|
229
|
+
f"xml_fallback_error={type(fallback_exc).__name__}: {fallback_exc}. "
|
|
230
|
+
"This is usually a non-standard XLSX package (merged cells, "
|
|
231
|
+
"charts/drawings, styles, or relationships). Do not retry the "
|
|
232
|
+
"same command blindly; inspect the workbook with "
|
|
233
|
+
"scripts/office/unpack.py or use Excel/LibreOffice to resave it."
|
|
234
|
+
),
|
|
235
|
+
"openpyxl_error": str(exc),
|
|
236
|
+
"openpyxl_error_type": type(exc).__name__,
|
|
237
|
+
"xml_fallback_error": str(fallback_exc),
|
|
238
|
+
"xml_fallback_error_type": type(fallback_exc).__name__,
|
|
239
|
+
"compatibility_hint": _openpyxl_compat_hint(exc),
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _scan_for_errors(target: Path) -> dict:
|
|
244
|
+
"""Read the workbook twice: computed values to find errors, then original formulas to count them."""
|
|
245
|
+
findings: dict[str, list[str]] = {token: [] for token in XLSX_ERROR_TOKENS}
|
|
246
|
+
error_count = 0
|
|
247
|
+
|
|
248
|
+
book = load_workbook(target, data_only=True)
|
|
249
|
+
try:
|
|
250
|
+
for sheet_name in book.sheetnames:
|
|
251
|
+
sheet = book[sheet_name]
|
|
252
|
+
for row in sheet.iter_rows():
|
|
253
|
+
for node in row:
|
|
254
|
+
value = node.value
|
|
255
|
+
if not isinstance(value, str):
|
|
256
|
+
continue
|
|
257
|
+
for token in XLSX_ERROR_TOKENS:
|
|
258
|
+
if token in value:
|
|
259
|
+
findings[token].append(
|
|
260
|
+
f"{sheet_name}!{node.coordinate}"
|
|
261
|
+
)
|
|
262
|
+
error_count += 1
|
|
263
|
+
break
|
|
264
|
+
finally:
|
|
265
|
+
book.close()
|
|
266
|
+
|
|
267
|
+
summary: dict[str, dict] = {}
|
|
268
|
+
for token, places in findings.items():
|
|
269
|
+
if places:
|
|
270
|
+
summary[token] = {
|
|
271
|
+
"count": len(places),
|
|
272
|
+
"locations": places[:_MAX_LOCATIONS_PER_TOKEN],
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
formula_total = _count_formulas(target)
|
|
276
|
+
|
|
277
|
+
return {
|
|
278
|
+
"status": "success" if error_count == 0 else "errors_found",
|
|
279
|
+
"total_errors": error_count,
|
|
280
|
+
"error_summary": summary,
|
|
281
|
+
"total_formulas": formula_total,
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _count_formulas(target: Path) -> int:
|
|
286
|
+
book = load_workbook(target, data_only=False)
|
|
287
|
+
try:
|
|
288
|
+
formula_total = 0
|
|
289
|
+
for sheet_name in book.sheetnames:
|
|
290
|
+
sheet = book[sheet_name]
|
|
291
|
+
for row in sheet.iter_rows():
|
|
292
|
+
for node in row:
|
|
293
|
+
cv = node.value
|
|
294
|
+
if isinstance(cv, str) and cv.startswith("="):
|
|
295
|
+
formula_total += 1
|
|
296
|
+
return formula_total
|
|
297
|
+
finally:
|
|
298
|
+
book.close()
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
# --- raw-XML fallback --------------------------------------------------------
|
|
302
|
+
# Trigger: LibreOffice expands a few original mergeCell entries to dozens of times their size;
|
|
303
|
+
# openpyxl parses the generated ref with ``min_col == None`` and raises
|
|
304
|
+
# ``TypeError: expected <class 'int'>``. This fallback avoids openpyxl,
|
|
305
|
+
# using stdlib zipfile + ElementTree for the same statistics.
|
|
306
|
+
_NS_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
|
|
307
|
+
_NS_PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships"
|
|
308
|
+
_NS_DOC_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _scan_for_errors_via_xml(target: Path, openpyxl_error: Exception | str) -> dict:
|
|
312
|
+
"""Pure-stdlib equivalent of :func:`_scan_for_errors`.
|
|
313
|
+
|
|
314
|
+
Used when LibreOffice rewrites a workbook in a form openpyxl cannot
|
|
315
|
+
re-read (typically merged-cell ``ref`` mutations that yield ``min_col``
|
|
316
|
+
of ``None``). Walks ``xl/worksheets/sheet*.xml`` directly, counts
|
|
317
|
+
``<f>`` elements as formulas, and looks for the seven Excel error
|
|
318
|
+
tokens inside cached ``<v>`` values. Returns the same JSON schema as
|
|
319
|
+
the openpyxl path with an extra ``warning`` field so callers can tell
|
|
320
|
+
which scanner produced the verdict.
|
|
321
|
+
"""
|
|
322
|
+
import zipfile
|
|
323
|
+
from xml.etree import ElementTree as ET
|
|
324
|
+
|
|
325
|
+
findings: dict[str, list[str]] = {token: [] for token in XLSX_ERROR_TOKENS}
|
|
326
|
+
formula_total = 0
|
|
327
|
+
|
|
328
|
+
with zipfile.ZipFile(target, "r") as zf:
|
|
329
|
+
sheet_display = _build_sheet_display_map(zf, ET)
|
|
330
|
+
|
|
331
|
+
for entry in sorted(zf.namelist()):
|
|
332
|
+
if not entry.startswith("xl/worksheets/sheet") or not entry.endswith(".xml"):
|
|
333
|
+
continue
|
|
334
|
+
display = sheet_display.get(entry, entry.split("/")[-1])
|
|
335
|
+
tree = ET.fromstring(zf.read(entry))
|
|
336
|
+
for cell in tree.iter(f"{{{_NS_MAIN}}}c"):
|
|
337
|
+
if cell.find(f"{{{_NS_MAIN}}}f") is not None:
|
|
338
|
+
formula_total += 1
|
|
339
|
+
v_node = cell.find(f"{{{_NS_MAIN}}}v")
|
|
340
|
+
if v_node is None or not v_node.text:
|
|
341
|
+
continue
|
|
342
|
+
vtext = v_node.text.strip()
|
|
343
|
+
for token in XLSX_ERROR_TOKENS:
|
|
344
|
+
if vtext.startswith(token):
|
|
345
|
+
findings[token].append(
|
|
346
|
+
f"{display}!{cell.get('r', '?')}"
|
|
347
|
+
)
|
|
348
|
+
break
|
|
349
|
+
|
|
350
|
+
error_count = sum(len(places) for places in findings.values())
|
|
351
|
+
summary: dict[str, dict] = {
|
|
352
|
+
token: {
|
|
353
|
+
"count": len(places),
|
|
354
|
+
"locations": places[:_MAX_LOCATIONS_PER_TOKEN],
|
|
355
|
+
}
|
|
356
|
+
for token, places in findings.items()
|
|
357
|
+
if places
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
"status": "success" if error_count == 0 else "errors_found",
|
|
362
|
+
"total_errors": error_count,
|
|
363
|
+
"error_summary": summary,
|
|
364
|
+
"total_formulas": formula_total,
|
|
365
|
+
"warning": (
|
|
366
|
+
"openpyxl could not parse the post-recalc workbook "
|
|
367
|
+
f"({type(openpyxl_error).__name__ if isinstance(openpyxl_error, Exception) else 'Error'}: {openpyxl_error}); "
|
|
368
|
+
"verified via raw XML scan instead. LibreOffice did complete the recalculation."
|
|
369
|
+
),
|
|
370
|
+
"scanner": "raw_xml_fallback",
|
|
371
|
+
"openpyxl_error_type": type(openpyxl_error).__name__ if isinstance(openpyxl_error, Exception) else "Error",
|
|
372
|
+
"openpyxl_error": str(openpyxl_error),
|
|
373
|
+
"compatibility_hint": _openpyxl_compat_hint(openpyxl_error),
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _build_sheet_display_map(zf, et_module) -> dict[str, str]:
|
|
378
|
+
"""Map ``xl/worksheets/sheetN.xml`` → user-visible sheet name.
|
|
379
|
+
|
|
380
|
+
Returns the underlying entry path keyed by display name so the JSON
|
|
381
|
+
locations match what reviewers see in Excel rather than zip internals.
|
|
382
|
+
"""
|
|
383
|
+
wb_root = et_module.fromstring(zf.read("xl/workbook.xml"))
|
|
384
|
+
rels_root = et_module.fromstring(zf.read("xl/_rels/workbook.xml.rels"))
|
|
385
|
+
|
|
386
|
+
rid_to_target: dict[str, str] = {}
|
|
387
|
+
for rel in rels_root.findall(f"{{{_NS_PKG_REL}}}Relationship"):
|
|
388
|
+
rid_to_target[rel.get("Id", "")] = rel.get("Target", "")
|
|
389
|
+
|
|
390
|
+
display: dict[str, str] = {}
|
|
391
|
+
for sheet_node in wb_root.findall(
|
|
392
|
+
f"{{{_NS_MAIN}}}sheets/{{{_NS_MAIN}}}sheet"
|
|
393
|
+
):
|
|
394
|
+
rid = sheet_node.get(f"{{{_NS_DOC_REL}}}id", "")
|
|
395
|
+
target = rid_to_target.get(rid, "").lstrip("./").lstrip("/")
|
|
396
|
+
if not target:
|
|
397
|
+
continue
|
|
398
|
+
entry = target if target.startswith("xl/") else f"xl/{target}"
|
|
399
|
+
display[entry] = sheet_node.get("name") or entry
|
|
400
|
+
return display
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
# --- Compatibility wrapper: existing ``from recalc import recalc`` callers still work ---
|
|
404
|
+
def recalc(filename, timeout=30):
|
|
405
|
+
"""Compatibility shim around :func:`recalculate_workbook`."""
|
|
406
|
+
return recalculate_workbook(filename, timeout_sec=timeout)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
# --- CLI entry point ---------------------------------------------------------
|
|
410
|
+
def _build_argparser() -> argparse.ArgumentParser:
|
|
411
|
+
parser = argparse.ArgumentParser(
|
|
412
|
+
prog="recalc.py",
|
|
413
|
+
description=(
|
|
414
|
+
"Recalculate every formula in an .xlsx workbook through LibreOffice "
|
|
415
|
+
"and emit a JSON report of remaining error markers."
|
|
416
|
+
),
|
|
417
|
+
epilog=(
|
|
418
|
+
"Output JSON keys: status, total_errors, total_formulas, error_summary; "
|
|
419
|
+
"or {\"error\": ...} on failure. Tokens scanned: "
|
|
420
|
+
+ ", ".join(XLSX_ERROR_TOKENS)
|
|
421
|
+
+ "."
|
|
422
|
+
),
|
|
423
|
+
)
|
|
424
|
+
parser.add_argument(
|
|
425
|
+
"workbook_path",
|
|
426
|
+
help="Path to the .xlsx (or .xlsm) file to recalculate.",
|
|
427
|
+
)
|
|
428
|
+
parser.add_argument(
|
|
429
|
+
"timeout_seconds",
|
|
430
|
+
nargs="?",
|
|
431
|
+
type=int,
|
|
432
|
+
default=30,
|
|
433
|
+
help="LibreOffice subprocess timeout in seconds (default: 30).",
|
|
434
|
+
)
|
|
435
|
+
return parser
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def main(argv: list[str] | None = None) -> None:
|
|
439
|
+
parser = _build_argparser()
|
|
440
|
+
args = parser.parse_args(argv)
|
|
441
|
+
payload = recalculate_workbook(
|
|
442
|
+
args.workbook_path, timeout_sec=args.timeout_seconds
|
|
443
|
+
)
|
|
444
|
+
print(json.dumps(payload, indent=2))
|
|
445
|
+
if "error" in payload and payload.get("status") is None:
|
|
446
|
+
sys.exit(2)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
if __name__ == "__main__":
|
|
450
|
+
main()
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-Z6BHCXKT.js";import"./chunk-4PDIO3M6.js";import"./chunk-IWK7PZP7.js";import"./chunk-EYK25HWR.js";import"./chunk-FXOH6TEQ.js";import"./chunk-XFCC2CI2.js";import"./chunk-N5SVBCUB.js";import"./chunk-HNWBFJNO.js";import"./chunk-XQK7JM66.js";export{a as ACCOUNT_EXIT,b as AlranAccountError,o as OTTILI_MODEL_LISTING,p as colourAvailability,c as defaultAccountCommandIo,f as formatMicroUsd,g as formatTable,e as gatewayCall,m as modelKeyOf,d as platformCall,u as registerAccountCommands,t as runAccountAction,i as runAuthLogin,j as runAuthLogout,h as runAuthStatus,s as runBilling,n as runConfigModel,l as runConfigProject,q as runModels,k as runSwitchCompany,r as runUsage};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a,b,c,d}from"./chunk-WWNUAU4P.js";import"./chunk-N6W7ZL26.js";import"./chunk-J3KCPYZT.js";import"./chunk-3AODGLMF.js";import"./chunk-VLXX22YO.js";import"./chunk-7XYOYZX2.js";import"./chunk-XQK7JM66.js";export{a as DEFAULT_THINKING_MODEL_IDS,b as isDefaultThinkingModelId,c as streamAnthropic,d as streamSimpleAnthropic};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{c as a}from"./chunk-44VPC5LA.js";import"./chunk-LZJYNT32.js";import"./chunk-GP52JZMY.js";import"./chunk-4X22UJQH.js";import"./chunk-6255CZPL.js";import"./chunk-ZQKVUPKA.js";import"./chunk-ZQOALVGL.js";import"./chunk-XFCC2CI2.js";import"./chunk-N5SVBCUB.js";import"./chunk-XQK7JM66.js";export{a as AlranUpdateApplication};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{d as b,e as c,f as d}from"./chunk-Z6HBNJCA.js";import"./chunk-4PDIO3M6.js";import{p as a}from"./chunk-IWK7PZP7.js";import"./chunk-EYK25HWR.js";import"./chunk-FXOH6TEQ.js";import"./chunk-XFCC2CI2.js";import"./chunk-N5SVBCUB.js";import"./chunk-HNWBFJNO.js";import"./chunk-XQK7JM66.js";export{a as platformIdempotencyKey,d as platformSessionClient,b as runTuiLogin,c as runTuiLogout};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a as h}from"./chunk-U3RMPDXU.js";import{b as c}from"./chunk-XAGZ6ZEU.js";import{a as R,b as E,c as O}from"./chunk-U7U3DJHF.js";import"./chunk-QKBN5CGI.js";import"./chunk-J3KCPYZT.js";import{a as f}from"./chunk-3AODGLMF.js";import{e as l,f as d,h as g,j as A}from"./chunk-VLXX22YO.js";import"./chunk-7XYOYZX2.js";import"./chunk-XQK7JM66.js";var S="v1";var I=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);function w(r){const n=new Map;if(!r)return n;for(const e of r.split(",")){const t=e.trim();if(!t)continue;const[a,s]=t.split("=",2);if(!a||!s)continue;n.set(a.trim(),s.trim())}return n}function N(r,n){if(n?.azureDeploymentName){return n.azureDeploymentName}const e=w(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(r.id);return e||r.id}function U(r){if(r instanceof Error){const n=r.status;const e=typeof n==="number"?n:void 0;if(e!==void 0){return`Azure OpenAI API error (${e}): ${r.message}`}return r.message}try{return JSON.stringify(r)}catch{return String(r)}}var _=(r,n,e)=>{const t=new d;(async()=>{const a=N(r,e);const s={role:"assistant",content:[],api:"azure-openai-responses",provider:r.provider,model:r.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const o=e?.apiKey;if(!o){throw new Error(`No API key for provider: ${r.provider}`)}const i=P(r,o,e);let p=x(r,n,e,a);const u=await e?.onPayload?.(p,r);if(u!==void 0){p=u}const z={...e?.signal?{signal:e.signal}:{},...e?.timeoutMs!==void 0?{timeout:e.timeoutMs}:{},maxRetries:e?.maxRetries??0};const{data:y,response:m}=await i.responses.create(p,z).withResponse();await e?.onResponse?.({status:m.status,headers:f(m.headers)},r);t.push({type:"start",partial:s});await O(y,s,t,r);if(e?.signal?.aborted){throw new Error("Request was aborted")}if(s.stopReason==="aborted"||s.stopReason==="error"){throw new Error("An unknown error occurred")}t.push({type:"done",reason:s.stopReason,message:s});t.end()}catch(o){g(e?.onProviderError,o,r);for(const i of s.content){delete i.index;delete i.partialJson}s.stopReason=e?.signal?.aborted?"aborted":"error";s.errorMessage=U(o);t.push({type:"error",reason:s.stopReason,error:s});t.end()}})();return t};var Z=(r,n,e)=>{const t=e?.apiKey;if(!t){throw new Error(`No API key for provider: ${r.provider}`)}const a=A(r,e,t);const s=e?.reasoning?l(r,e.reasoning):void 0;const o=s==="off"?void 0:s;return _(r,n,{...a,reasoningEffort:o})};function v(r){const n=r.trim().replace(/\/+$/,"");let e;try{e=new URL(n)}catch{throw new Error(`Invalid Azure OpenAI base URL: ${r}`)}const t=e.hostname.endsWith(".openai.azure.com")||e.hostname.endsWith(".cognitiveservices.azure.com");const a=e.pathname.replace(/\/+$/,"");if(t&&(a===""||a==="/"||a==="/openai")){e.pathname="/openai/v1";e.search=""}return e.toString().replace(/\/+$/,"")}function M(r){return`https://${r}.openai.azure.com/openai/v1`}function b(r,n){const e=n?.azureApiVersion||process.env.AZURE_OPENAI_API_VERSION||S;const t=n?.azureBaseUrl?.trim()||process.env.AZURE_OPENAI_BASE_URL?.trim()||void 0;const a=n?.azureResourceName||process.env.AZURE_OPENAI_RESOURCE_NAME;let s=t;if(!s&&a){s=M(a)}if(!s&&r.baseUrl){s=r.baseUrl}if(!s){throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.")}return{baseUrl:v(s),apiVersion:e}}function P(r,n,e){const t={...r.headers};if(e?.headers){Object.assign(t,e.headers)}const{baseUrl:a,apiVersion:s}=b(r,e);return new c({apiKey:n,apiVersion:s,dangerouslyAllowBrowser:true,defaultHeaders:t,baseURL:a})}function x(r,n,e,t){const a=R(r,n,I);const s={model:t,input:a,stream:true,prompt_cache_key:h(e?.sessionId),store:false};if(e?.maxTokens){s.max_output_tokens=e?.maxTokens}if(e?.temperature!==void 0){s.temperature=e?.temperature}if(n.tools&&n.tools.length>0){s.tools=E(n.tools)}if(r.reasoning){if(e?.reasoningEffort||e?.reasoningSummary){const o=e?.reasoningEffort?r.thinkingLevelMap?.[e.reasoningEffort]??e.reasoningEffort:"medium";s.reasoning={effort:o,summary:e?.reasoningSummary||"auto"};s.include=["reasoning.encrypted_content"]}else if(r.thinkingLevelMap?.off!==null){s.reasoning={effort:r.thinkingLevelMap?.off??"none"}}}return s}export{_ as streamAzureOpenAIResponses,Z as streamSimpleAzureOpenAIResponses};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
var C=["local-task:","local-background-task:","team-plan:"];var N=new Set(["explore","worker","verifier"]);function S(e){return e.sessionKind==="task"||C.some(n=>e.purpose?.startsWith(n))}function v(e){if(e.sessionType!=="branch"||!e.parentSessionId){return false}return S(e)}function D(e){const n=e.agentName?.trim().toLocaleLowerCase();return n!==void 0&&N.has(n)}function Se(e){return S(e)||D(e)}function be(e,n){const r=[];const t=new Set;const i=new Set([n]);let s=true;while(s){s=false;for(const o of e){if(t.has(o.sessionId)||!v(o)||!i.has(o.parentSessionId)){continue}r.push(o);t.add(o.sessionId);i.add(o.sessionId);s=true}}return r}function Me(e){return{sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.agentName?{agentName:e.agentName}:{},...e.title?{task:e.title}:{},status:O(e.status),...h("createdAtMs",e.createdAt),...h("updatedAtMs",e.updatedAt),...e.errorMessage?{errorMessage:e.errorMessage}:{}}}function Ie(e){return e.status==="queued"||e.status==="running"}function O(e){const n=e?.trim().toLocaleLowerCase().replaceAll("-","_");if(!n)return"unknown";if(n==="queued"||n==="pending"||n==="created"){return"queued"}if(n==="running"||n==="started"||n==="active"||n==="busy"||n==="processing"||n==="in_progress"){return"running"}if(n==="finished"||n==="completed"||n==="succeeded"||n==="success"){return"completed"}if(n==="idle")return"completed";if(n==="error"||n==="failed"||n==="lost")return"failed";if(n==="aborted"||n==="interrupted"||n==="cancelled"||n==="canceled"||n==="stopped"){return"stopped"}return"unknown"}function h(e,n){if(typeof n==="number"&&Number.isFinite(n))return{[e]:n};if(typeof n!=="string")return{};const r=Number(n);if(Number.isFinite(r))return{[e]:r};const t=Date.parse(n);return Number.isFinite(t)?{[e]:t}:{}}var Ae="alran";var k=64*1024;var L=400;function I(e){const n=K(e.toolName);const r=g(e.input);if(!n)return void 0;const t=W(e.status,e.error);const i=V(n)?B(r??{},e.output):$(n)?r?z(r):[]:[];if(i.length===0)return void 0;return{schemaVersion:1,state:t,blocks:i}}function B(e,n){const r=p(e,["path","filePath","file_path"]);const t=F(n);if(t){return[t.omitted===void 0?b(r,t.diff):j(r,t.diff,t.omitted)]}return U(e).map(({oldText:i,newText:s})=>{const o=[...i.split("\n").map(d=>`- ${d}`),...s.split("\n").map(d=>`+ ${d}`)].join("\n");return b(r,o)})}function z(e){const n=p(e,["path","filePath","file_path"]);const r=p(e,["content","fileContent","file_content"]);if(r===void 0)return[];const t=m(r);if(r.includes("\0")){return[{kind:"summary",...n?{path:n}:{},message:"Binary content cannot be previewed safely.",reason:"binary",byteCount:t}]}if(t>k){return[{kind:"summary",...n?{path:n}:{},message:`File preview omitted because it is ${Y(t)}.`,reason:"too-large",byteCount:t}]}return[{kind:"file",...n?{path:n}:{},content:r,lineCount:r.split("\n").length,truncated:false}]}function b(e,n){const r=n.split("\n");const t=m(n);const i=r.slice(0,L);const s=t>k;let o=i.join("\n");if(s)o=H(o,k);const d=Math.max(0,r.length-o.split("\n").length);return{kind:"diff",...e?{path:e}:{},diff:o,addedLines:M(r,"+"),removedLines:M(r,"-"),truncated:d>0||s,...d>0?{omittedLines:d}:{}}}function j(e,n,r){return{kind:"summary",...e?{path:e}:{},message:n,reason:r==="timeout"?"unavailable":"too-large"}}function F(e){const n=g(e);if(!n)return void 0;const r=[n,g(n.result),g(n.output)].filter(t=>t!==void 0);for(const t of r){const i=g(t.details);const s=i?p(i,["diff","previewDiff","preview_diff"]):void 0;if(s){const o=i?p(i,["diffOmitted","diff_omitted"]):void 0;return o===void 0?{diff:s}:{diff:s,omitted:o}}}return void 0}function U(e){const n=X(e.edits);const r=(n??[]).flatMap(s=>{const o=g(s);const d=o?p(o,["oldText","old_text"]):void 0;const f=o?p(o,["newText","new_text"]):void 0;return d!==void 0&&f!==void 0?[{oldText:d,newText:f}]:[]});const t=p(e,["oldText","old_text"]);const i=p(e,["newText","new_text"]);if(t!==void 0&&i!==void 0){r.push({oldText:t,newText:i})}return r}function W(e,n){if(G(n)||J(e))return"not-applied";return q(e)?"applied":"proposed"}function q(e){return e===2||e==="2"||e==="completed"||e==="complete"||e==="done"||e==="finished"||e==="succeeded"||e==="success"}function J(e){return e===3||e==="3"||e==="failed"||e==="error"}function G(e){return e!==void 0&&e!==null&&e!==""}function K(e){const n=e?.trim().toLocaleLowerCase().replace(/[^a-z0-9]/gu,"");return n||void 0}function V(e){return e==="edit"||e==="editfile"||e==="replace"}function $(e){return e==="write"||e==="writefile"||e==="createfile"}function g(e){const n=R(e);return n!==null&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function X(e){const n=R(e);return Array.isArray(n)?n:void 0}function R(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return void 0}}function p(e,n){for(const r of n){const t=e[r];if(typeof t==="string")return t}return void 0}function M(e,n){return e.filter(r=>r.startsWith(n)&&!r.startsWith(n.repeat(3))).length}function m(e){return new TextEncoder().encode(e).byteLength}function H(e,n){if(m(e)<=n)return e;let r=0;let t=e.length;while(r<t){const i=Math.ceil((r+t)/2);if(m(e.slice(0,i))<=n)r=i;else t=i-1}return e.slice(0,r)}function Y(e){if(e<1024)return`${e} B`;return`${(e/1024).toFixed(e<10*1024?1:0)} KiB`}var Q=2;var Z=6;var ee=10;var ne=3;var te=4;function Ce(e,n){const r=e.dataJson?.trim();if(!r)return void 0;if(r==="[DONE]")return A({type:"done",turnId:n},e);let t;try{t=JSON.parse(r)}catch{return void 0}const i=a(t);if(!i)return void 0;const s=u(i,["turn_id","turnId"])??n;const o=i.type;let d;if(o===ee||o==="heartbeat"){d={type:"heartbeat",turnId:s}}else if(o===Q||o==="agent_message"){const f=a(i.agent_message)??a(i.agentMessage);d=f?ie(f,s):void 0}else if(re(i)){const f=a(i.agent_message_chunk)??a(i.agentMessageChunk);d=f?oe(f,s):void 0}else if(o==="error"){d={type:"error",message:u(i,["error","message"])??"Runtime stream failed",turnId:s}}else if(o==="session_status"){d=ue(i,s)}else if(o===ne||o===te){d=de(i,s)}else if(o==="resume_overflow"){d={type:"resync-required",turnId:s}}else if(typeof o==="string"){const f={...i};delete f.type;delete f.turnId;d={type:"generic",eventType:o,data:f,turnId:s}}return d?A(d,e):void 0}function re(e){return e.type===Z&&("agent_message_chunk"in e||"agentMessageChunk"in e)||e.type==="agent_message_chunk"}function ie(e,n){const r=se(e,n);if(r)return r;const t=x(e,n);if(t.role==="unknown")return void 0;if(t.role==="assistant"&&t.finishReason==="error"){return{type:"error",message:t.content?.trim()||"Runtime stream failed",turnId:n}}return{type:"message",message:t}}function oe(e,n){const r=x(e,n);if(r.role!=="assistant")return void 0;return l({type:"delta",messageId:r.id,turnId:r.turnId??n,role:r.role,content:r.content,thinking:r.thinking,toolCalls:r.toolCalls,timestamp:r.timestamp,chunkIndex:c(e,["chunk_index","chunkIndex"]),finish:e.finish===true?true:void 0})}function se(e,n){const r=u(e,["msg_content","msgContent","content"]);if(!r)return void 0;let t;try{t=a(JSON.parse(r))}catch{return void 0}const i=t?u(t,["eventType"]):void 0;if(!t||!i)return void 0;const s=c(e,["msg_type","msgType","message_type","messageType"])===3;if(!s&&!["session.spawned","communication.message","delegation.message","todo_updated"].includes(i)){return void 0}const o={...t};delete o.eventType;return l({type:"generic",eventType:i,data:o,turnId:u(e,["turn_id","turnId"])??n,messageId:u(e,["msg_id","msgId","id"]),timestamp:c(e,["timestamp"])})}function ue(e,n){const r=a(e.session_status)??{};const t=ae(u(r,["type","status"]));return t?l({type:"session-status",status:t,message:u(r,["message"]),turnId:n}):void 0}function de(e,n){const r=a(e.payload)??{};const t=ce(c(r,["status"]));if(!t)return void 0;const i=a(r.error);return l({type:"session-status",status:t,message:u(i??r,["message","detail"]),turnId:n})}function ae(e){if(e==="idle"||e==="started"||e==="finished"||e==="error"||e==="aborted"||e==="interrupted"){return e}return void 0}function ce(e){if(e===1||e===2)return"started";if(e===3)return"idle";if(e===4)return"error";if(e===5)return"aborted";if(e===6)return"finished";return void 0}function A(e,n){return n.cursor?{...e,cursor:n.cursor}:e}function x(e,n){return le(a(e)??{},n)}function le(e,n){const r=a(y(e.rawJson??e.raw_json))??{};return l({id:u(e,["msg_id","msgId","id"]),turnId:u(e,["turn_id","turnId"])??n,role:ke(u(e,["role"]))??"unknown",kind:me(u(e,["kind"])),source:u(e,["source"]),origin:y(e.origin??e.originJson??e.origin_json),error:u(e,["error"]),tokensBefore:c(e,["tokensBefore","tokens_before"]),tokensAfter:c(e,["tokensAfter","tokens_after"]),content:u(e,["msg_content","msgContent","content"]),editContent:u(e,["editContent"])??u(r,["editContent"]),thinking:u(e,["thinking_content","thinkingContent","thinking"]),thinkingDurationMs:c(e,["thinking_duration_ms","thinkingDurationMs"]),toolCalls:_e(E(T(e,["tool_calls","toolCalls"])),r),toolResult:ge(a(e.toolResult??e.tool_result)),parts:Te(T(e,["parts"])),attachments:ye(T(e,["attachments"])),timestamp:c(e,["timestamp","createdAt","created_at"]),finishReason:u(e,["finish_reason","finishReason"]),usage:pe(a(e.usage)),actions:fe(a(e.actions))})}function fe(e){if(!e)return void 0;const n=l({fork:P(e,["fork"]),rewind:P(e,["rewind"])});return Object.keys(n).length>0?n:void 0}function pe(e){if(!e)return void 0;const n=l({totalTokens:c(e,["total_tokens","totalTokens"]),inputTokens:c(e,["input_tokens","inputTokens"]),outputTokens:c(e,["output_tokens","outputTokens"]),reasoningTokens:c(e,["reasoning","reasoning_tokens","reasoningTokens"]),requestDurationMs:c(e,["request_duration_ms","requestDurationMs"]),decodeDurationMs:c(e,["decode_duration_ms","decodeDurationMs"]),cacheReadTokens:c(e,["cache_read","cacheRead","cache_read_tokens"]),cacheWriteTokens:c(e,["cache_write","cacheWrite","cache_write_tokens"])});return Object.keys(n).length>0?n:void 0}function ge(e){if(!e)return void 0;const n=u(e,["toolCallId","tool_call_id"]);if(!n)return void 0;const r=a(e.details);const t=r?l({taskId:u(r,["taskId","task_id"]),subSessionId:u(r,["subSessionId","sub_session_id"]),subTurnId:u(r,["subTurnId","sub_turn_id"])}):void 0;return l({toolCallId:n,toolName:u(e,["toolName","tool_name"]),details:t&&Object.keys(t).length>0?t:void 0})}function me(e){if(e==="preamble"||e==="final"||e==="compaction_start"||e==="compaction"||e==="compaction_failed"||e==="review_start"||e==="review_result"||e==="review_failed"||e==="review_aborted"||e==="review_interrupted"){return e}return void 0}function Ne(e){if(e.parts?.length)return[...e.parts];return[...e.thinking?.trim()?[l({type:"thinking",content:e.thinking,durationMs:e.thinkingDurationMs})]:[],...e.content?.trim()?[{type:"text",content:e.content}]:[],...(e.toolCalls??[]).map(n=>({type:"tool",toolCall:n}))]}function Te(e){if(!e)return void 0;const n=e.flatMap(r=>{const t=a(r);if(!t)return[];const i=u(t,["id","part_id","partId"]);const s=u(t,["type","kind"]);if(s==="thinking"||s==="cognitive_text"){const o=u(t,["content","text","thinking"]);if(o===void 0)return[];return[l({id:i,type:"thinking",content:o,durationMs:c(t,["durationMs","duration_ms"])})]}if(s==="text"){const o=u(t,["content","text"]);return o===void 0?[]:[l({id:i,type:"text",content:o})]}if(s==="tool"||s==="tool_call"||s==="toolCall"){const o=a(t.toolCall??t.tool_call)??t;const[d]=E([o])??[];return d?[l({id:i,type:"tool",toolCall:d})]:[]}return[]});return n.length>0?n:void 0}function ye(e){if(!e)return void 0;const n=e.flatMap(r=>{const t=a(r);if(!t)return[];const i=a(t.meta)??t;const s=a(t.local);const o=a(t.cloud);const d=u(i,["mimeType","mime_type"])??u(t,["mimeType","mime_type"])??"application/octet-stream";const f=u(i,["attachmentType","attachment_type","type"])??u(t,["attachmentType","attachment_type","type"]);return[l({type:f==="image"||d.startsWith("image/")?"image":"file",fileName:u(i,["fileName","file_name"])??u(t,["fileName","file_name"])??"attachment",mimeType:d,sizeBytes:c(i,["sizeBytes","size_bytes"]),filePath:(s?u(s,["filePath","file_path"]):void 0)??u(t,["filePath","file_path"]),assetId:s?u(s,["assetId","asset_id"]):void 0,previewUrl:u(t,["previewUrl","preview_url"])??(o?u(o,["url"]):void 0)})]});return n.length>0?n:void 0}function E(e){if(!e)return void 0;const n=e.flatMap(r=>{const t=a(r);if(!t)return[];const i=u(t,["tool_name","tool_call_name","toolName","name"]);if(!i)return[];const s=l({id:u(t,["tool_call_id","toolCallId","id"]),parentToolCallId:u(t,["parent_tool_call_id","parentToolCallId"])?.trim()||void 0,name:i,status:u(t,["tool_call_status","toolCallStatus","status"])??c(t,["tool_call_status","toolCallStatus","status"]),input:y(w(t,["tool_call_args","toolCallArgs","args","arguments","input"])),output:y(w(t,["tool_call_result_data","toolCallResultData","tool_call_result","toolCallResult","result","output"])),error:w(t,["tool_call_error","toolCallError","error"]),durationMs:c(t,["tool_call_duration_ms","toolCallDurationMs","durationMs","duration_ms"])});const o=I({toolName:s.name,status:s.status,input:s.input,output:s.output,error:s.error});return[{...s,...o?{structuredPreview:o}:{}}]});return n.length>0?n:void 0}function _e(e,n){if(!e?.some(t=>t.id&&!t.parentToolCallId))return e;const r=new Map;for(const t of T(n,["tool_calls","toolCalls"])??[]){const i=a(t);if(!i)continue;const s=u(i,["tool_call_id","toolCallId","id"]);const o=u(i,["parent_tool_call_id","parentToolCallId"]);if(s&&o)r.set(s,o)}if(r.size===0)return e;return e.map(t=>{const i=t.parentToolCallId??(t.id?r.get(t.id):void 0);return i&&i!==t.parentToolCallId?{...t,parentToolCallId:i}:t})}function ke(e){if(e==="user"||e==="assistant"||e==="system")return e;return e===void 0?void 0:"unknown"}function a(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function u(e,n){for(const r of n){if(typeof e[r]==="string")return e[r]}return void 0}function c(e,n){for(const r of n){const t=e[r];if(typeof t==="number"&&Number.isFinite(t))return t;if(typeof t==="string"&&t.trim()){const i=Number(t);if(Number.isFinite(i))return i}}return void 0}function P(e,n){for(const r of n){if(typeof e[r]==="boolean")return e[r]}return void 0}function T(e,n){for(const r of n){if(Array.isArray(e[r]))return e[r]}return void 0}function w(e,n){for(const r of n){if(Object.prototype.hasOwnProperty.call(e,r))return e[r]}return void 0}function y(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function l(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}var _=["default","auto","bypassPermissions"];var we={default:"Ask",auto:"Auto",bypassPermissions:"Full access",off:"Off"};var he={default:"ASK",auto:"AUTO",bypassPermissions:"FULL",off:"OFF"};function De(e){return _.find(n=>n===e)}function Oe(e){return we[e]}function Le(e){return he[e]}function Be(e){return e==="bypassPermissions"}function ze(e){if(e==="off")return"default";const n=_.indexOf(e);return _[(n+1)%_.length]}export{v as a,D as b,Se as c,be as d,Me as e,Ie as f,I as g,Ce as h,x as i,Ne as j,_ as k,De as l,Oe as m,Le as n,Be as o,ze as p,Ae as q};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a as o,b as l,c,d as m,e as d,f as h,g as f,i as v,j as w,k as y}from"./chunk-CJM7ZJ6W.js";var S=class extends h{async evalCodeAsync(e,t="eval.js",s){let i=s===void 0?1:0,n=d(s),r=0;try{r=await this.memory.newHeapCharPointer(e).consume(a=>this.ffi.QTS_Eval_MaybeAsync(this.ctx.value,a.value.ptr,a.value.strlen,t,i,n))}catch(a){throw this.runtime.debugLog("QTS_Eval_MaybeAsync threw",a),a}let u=this.ffi.QTS_ResolveException(this.ctx.value,r);return u?(this.ffi.QTS_FreeValuePointer(this.ctx.value,r),this.fail(this.memory.heapValueHandle(u))):this.success(this.memory.heapValueHandle(r))}newAsyncifiedFunction(e,t){return this.newFunction(e,t)}};var x=class extends f{constructor(e){super(e)}newContext(e={}){let t=m(e.intrinsics),s=new l(this.ffi.QTS_NewContext(this.rt.value,t),void 0,n=>{this.contextMap.delete(n),this.callbacks.deleteContext(n),this.ffi.QTS_FreeContext(n)}),i=new S({module:this.module,ctx:s,ffi:this.ffi,rt:this.rt,ownedLifetimes:[],runtime:this,callbacks:this.callbacks});return this.contextMap.set(s.value,i),i}setModuleLoader(e,t){super.setModuleLoader(e,t)}setMaxStackSize(e){return super.setMaxStackSize(e)}};var k=class extends y{constructor(e,t){super(e,t);this.ffi=t,this.module=e}newRuntime(e={}){let t=new l(this.ffi.QTS_NewRuntime(),void 0,i=>{this.callbacks.deleteRuntime(i),this.ffi.QTS_FreeRuntime(i)}),s=new x({module:this.module,ffi:this.ffi,rt:t,callbacks:this.callbacks});return v(s,e),e.moduleLoader&&s.setModuleLoader(e.moduleLoader),s}newContext(e={}){let t=this.newRuntime(),s=e.ownedLifetimes?e.ownedLifetimes.concat([t]):[t],i=t.newContext({...e,ownedLifetimes:s});return t.context=i,i}evalCode(){throw new o("QuickJSWASMModuleAsyncify.evalCode: use evalCodeAsync instead")}evalCodeAsync(e,t){return c.withScopeAsync(async s=>{let i=s.manage(this.newContext());w(i.runtime,t);let n=await i.evalCodeAsync(e,"eval.js");if(t.memoryLimitBytes!==void 0&&i.runtime.setMemoryLimit(-1),n.error)throw i.dump(s.manage(n.error));return i.dump(s.manage(n.value))})}};export{k as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
function o(e){const r={};for(const[t,n]of e.entries()){r[t]=n}return r}export{o as a};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a as y,c as A,d as p}from"./chunk-LZJYNT32.js";import{b as se}from"./chunk-GP52JZMY.js";import{a as re,b as $,c as ne,e as te,f as L,h as ae,i as ie}from"./chunk-4X22UJQH.js";import{b as z,d as H,f as X,h as b,i as G,k as x,l as Y,m as Z,n as W,o as Q,q,r as ee}from"./chunk-6255CZPL.js";import{a as U,b as I,c as j,d as F,e as K,f as V}from"./chunk-ZQKVUPKA.js";import{a as _e}from"./chunk-ZQOALVGL.js";import{o as S}from"./chunk-XFCC2CI2.js";import{e as Be}from"./chunk-XQK7JM66.js";var ge=Be(_e(),1);import{createHash as Je}from"node:crypto";import{existsSync as k,mkdirSync as ce,readFileSync as v,renameSync as de,rmSync as pe,writeFileSync as ue}from"node:fs";import{homedir as De}from"node:os";import c from"node:path";var je="https://cdn.ottili.one/alran-code";var Fe="ALRAN_UPDATE_SOURCE";var Ke=8e3;var R=class{currentVersion;installRoot;releaseBaseUrl;publicKey;environment;dependencies;constructor(e){this.currentVersion=I(e.currentVersion);this.installRoot=e.installRoot??C(e.environment);this.releaseBaseUrl=(e.releaseBaseUrl??(e.environment??process.env)[Fe]?.trim()??je).replace(/\/+$/u,"");if(!/^https:\/\//u.test(this.releaseBaseUrl)&&!/^http:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/u.test(this.releaseBaseUrl)){throw new Error(`Alran update source must be https: ${this.releaseBaseUrl}`)}this.publicKey=e.publicKey;this.environment=e.environment??process.env;this.dependencies={fetchBytes:Xe,installArtifact:Ge,validateInstalledVersion:Ye,...e.dependencies}}async check(e={}){A(e.signal);p(e,"checking",true);const n=e.channel?U(e.channel):ze(this.installRoot);const t=e.version?I(e.version):void 0;const a=t?`${this.releaseBaseUrl}/releases/${encodeURIComponent(t)}/manifest.json`:`${this.releaseBaseUrl}/channels/${n}.json`;const s=this.publicKey??He(this.installRoot,this.environment);const i=oe(e.timeoutMs);const o=new AbortController;const l=le(e.signal,o);let f=false;const d=setTimeout(()=>{f=true;o.abort(new Error(`Alran update check timed out after ${i}ms.`))},i);d.unref?.();try{const[u,h]=await Promise.all([this.dependencies.fetchBytes(a,{signal:o.signal,proxyEnvironment:this.environment}),this.dependencies.fetchBytes(`${a}.sig`,{signal:o.signal,proxyEnvironment:this.environment})]);const g=j(u,h.toString("utf8"),s);if(!t&&g.channel!==n){throw new Error(`Signed Alran release channel mismatch: expected ${n}, got ${g.channel}.`)}if(t&&g.version!==t){throw new Error(`Signed Alran release version mismatch: expected ${t}, got ${g.version}.`)}K(g,F());const m=V(this.currentVersion,g.version);return{status:m<0?"available":m>0?"ahead":"current",channel:n,currentVersion:this.currentVersion,latestVersion:g.version,manifest:g}}catch(u){if(e.signal?.aborted)throw new y;if(f){throw new Error(`Alran update check timed out after ${i}ms.`,{cause:u})}throw u}finally{clearTimeout(d);l()}}async apply(e={}){const n=await this.check(e);if(n.status==="current"){return{...n,applied:false,installRoot:this.installRoot}}if(n.status==="ahead"&&!e.version){throw new Error(`Installed Alran ${this.currentVersion} is newer than ${n.channel} ${n.latestVersion}; pass --to to downgrade explicitly.`)}const t=oe(e.timeoutMs);A(e.signal);p(e,"downloading",true);const a=new AbortController;const s=le(e.signal,a);let i=false;const o=setTimeout(()=>{i=true;a.abort(new Error(`Alran artifact download timed out after ${t}ms.`))},t);o.unref?.();let l;try{l=await this.dependencies.fetchBytes(n.manifest.installArtifact.url,{signal:a.signal,proxyEnvironment:this.environment})}catch(m){if(e.signal?.aborted)throw new y;if(i){throw new Error(`Alran artifact download timed out after ${t}ms.`,{cause:m})}throw m}finally{clearTimeout(o);s()}A(e.signal);Ze(l,n.manifest);const f=c.join(this.installRoot,"versions");const d=c.join(f,n.latestVersion);const u=c.join(f,`.staging-${n.latestVersion}-${process.pid}-${Date.now()}`);const h=c.join(u,`alran-alran-${n.latestVersion}.tgz`);ce(u,{recursive:true});let g=false;try{p(e,"staging",true);A(e.signal);ue(h,l,{mode:384});A(e.signal);p(e,"installing",false);await this.dependencies.installArtifact({artifact:h,prefix:u,registry:n.manifest.registry,proxyEnvironment:this.environment});A(e.signal);S(()=>pe(h,{force:true}));p(e,"validating",false);await this.dependencies.validateInstalledVersion(u,n.latestVersion);A(e.signal);p(e,"activating",false);if(k(d)){await this.dependencies.validateInstalledVersion(d,n.latestVersion);T(u)}else{S(()=>de(u,d));g=true}We(this.installRoot,n.latestVersion);p(e,"completed",false);return{...n,applied:true,installRoot:this.installRoot}}catch(m){T(u);if(g&&Qe(this.installRoot)!==n.latestVersion){T(d)}if(m instanceof y||e.signal?.aborted){throw new y}throw new Error(`Alran ${n.latestVersion} was not activated; the previous version is unchanged: ${me(m)}`,{cause:m})}}};function C(r=process.env){if(r.ALRAN_INSTALL_ROOT)return c.resolve(r.ALRAN_INSTALL_ROOT);if(process.platform==="win32"){const n=r.LOCALAPPDATA;if(!n)throw new Error("LOCALAPPDATA is required to resolve the Alran install root.");return c.join(n,"AlranCode")}const e=r.XDG_DATA_HOME||c.join(De(),".local","share");return c.join(e,"alran-code")}function ze(r){const e=c.join(r,"update.json");if(!k(e))return"stable";let n;try{n=JSON.parse(v(e,"utf8"))}catch(t){throw new Error(`Alran update channel config is invalid: ${me(t)}`)}if(typeof n!=="object"||n===null||!("channel"in n)||typeof n.channel!=="string"){throw new Error("Alran update channel config is missing channel.")}return U(n.channel)}function He(r,e){const n=e.ALRAN_RELEASE_PUBLIC_KEY_FILE;if(n)return v(c.resolve(n),"utf8");const t=c.join(r,"install.json");if(!k(t)){throw new Error("Alran update trust root is missing. Install with the official Shell/PowerShell installer first.")}const a=JSON.parse(v(t,"utf8"));if(typeof a.publicKey!=="string"||!a.publicKey.includes("BEGIN PUBLIC KEY")){throw new Error("Alran installer metadata does not contain a valid release public key.")}return a.publicKey}function oe(r){if(r===void 0)return Ke;if(!Number.isSafeInteger(r)||r<100||r>6e4){throw new Error("Alran update timeout must be an integer between 100 and 60000 milliseconds.")}return r}async function Xe(r,e={}){const[{default:n},{createTuiNetworkDispatcher:t}]=await Promise.all([import("./undici-TUGHZJSA.js"),import("./network-proxy-U72JCK2I.js")]);const a=t(e.proxyEnvironment);try{const s=await n.fetch(r,{signal:e.signal,dispatcher:a,redirect:"error"});if(!s.ok){throw new Error(`Alran release server returned HTTP ${s.status} for ${r}`)}return Buffer.from(await s.arrayBuffer())}finally{await a.close()}}async function Ge(r){const e=process.platform==="win32"?"npm.cmd":"npm";await fe(e,["install","--global","--prefix",r.prefix,r.artifact,"--registry",r.registry,"--no-audit","--no-fund","--package-lock=false"],r.proxyEnvironment,true)}async function Ye(r,e){let n=c.join(r,"bin","alran");let t=["--version"];if(process.platform==="win32"){const s=re(r,b().packageName);const i=JSON.parse(v(c.join(s,"package.json"),"utf8"));const o=ie(i.bin,"alran");if(!o||!k(c.join(r,"alran.cmd"))){throw new Error(`Installed Alran launcher is missing or invalid at ${r}.`)}n=process.execPath;t=[c.join(s,o),"--version"]}const a=await fe(n,t,process.env,true);if(a.trim()!==e){throw new Error(`Installed Alran version mismatch: expected ${e}, got ${a.trim()}`)}}function fe(r,e,n,t=false){return new Promise((a,s)=>{let i=false;const o=(0,ge.default)(r,e,{env:n,shell:false,stdio:t?["ignore","pipe","pipe"]:"inherit",windowsHide:true});const l=[];const f=[];o.stdout?.on("data",d=>l.push(d));o.stderr?.on("data",d=>f.push(d));o.once("error",d=>{if(i)return;i=true;s(d)});o.once("close",(d,u)=>{if(i)return;i=true;if(d===0)return a(Buffer.concat(l).toString("utf8"));const h=Buffer.concat(f).toString("utf8").trim();s(new Error(`${r} failed (${u?`signal ${u}`:`exit ${String(d)}`})${h?`: ${h}`:""}`))})})}function le(r,e){if(!r)return()=>void 0;const n=()=>e.abort(r.reason);if(r.aborted)n();else r.addEventListener("abort",n,{once:true});return()=>r.removeEventListener("abort",n)}function Ze(r,e){if(r.length!==e.installArtifact.size){throw new Error(`Alran artifact checksum/size verification failed: expected ${e.installArtifact.size} bytes, got ${r.length}.`)}const n=Je("sha256").update(r).digest("hex");if(n!==e.installArtifact.sha256){throw new Error("Alran artifact checksum verification failed.")}}function We(r,e){ce(r,{recursive:true});const n=c.join(r,"current");const t=`${n}.tmp-${process.pid}-${Date.now()}`;ue(t,`${e}
|
|
3
|
+
`,{mode:384});S(()=>de(t,n))}function T(r){pe(r,{recursive:true,force:true,maxRetries:4,retryDelay:50})}function Qe(r){const e=c.join(r,"current");if(!k(e))return void 0;return v(e,"utf8").trim()||void 0}function me(r){return r instanceof Error?r.message:String(r)}function Sr(r=process.env){return"A staged Alran update will activate after this process exits."}function Vr(r=process.env){return"Alran update was staged, but its activation journal could not be scheduled."}function he(r){return"Alran npm prefix updater received a non-prefix plan."}function Ae(r){return"Alran npm prefix ownership metadata is missing."}function Pe(r,e={}){if(e.blockingSessionCount===void 0){return`Alran ${r} is already staged. Restarting will resume activation after running Alran sessions exit.`}const n=Math.max(0,Math.trunc(e.blockingSessionCount));if(n>0){return`Alran ${r} is already staged. Activation will wait for ${String(n)} other Alran ${n===1?"session":"sessions"} to exit.`}return`Alran ${r} is already staged. It will activate after this process exits.`}function xe(r,e={}){if(e.blockingSessionCount===void 0){return`Alran ${r} is already active. Restarting will finish update cleanup after running Alran sessions exit.`}const n=Math.max(0,Math.trunc(e.blockingSessionCount));if(n>0){return`Alran ${r} is already active. Update cleanup will wait for ${String(n)} other Alran ${n===1?"session":"sessions"} to exit.`}return`Alran ${r} is already active. Restarting will finish update cleanup.`}function ye(r,e,n){return`Alran update staged ${r}; expected ${e}.`}function ve(r,e=process.env){const n=e.LC_ALL||e.LC_MESSAGES||e.LANG;return se(n,"update.versionedInstalled").replace("{version}",r)}function ke(r,e,n){return`Alran ${r} was not staged; the active installation is unchanged: ${e}`}import{randomUUID as N}from"node:crypto";import{chmodSync as qe,existsSync as O,mkdirSync as M,readdirSync as er,readFileSync as J,renameSync as be,rmSync as B,writeFileSync as $e}from"node:fs";import P from"node:path";var D="releases";var Re="current";var rr=".alran-update.lock";var nr=2;function Ne(r,e,n=process.platform){const t=E(n);return t.join(r,D,`.staging-${e}-${process.pid}-${N()}`)}function Me(r){M(r,{recursive:true,mode:448})}function Ue(r){const e=P.join(r,rr);M(e,{recursive:true,mode:448});const n=`${String(process.pid)}-${N()}.claim`;const t=P.join(e,n);$e(t,"choosing\n",{flag:"wx",mode:384});try{const s=Math.max(0,...Ee(e).map(o=>o.ticket??0))+1;w(t,`${String(s)}
|
|
4
|
+
`,384);const i=Ee(e).some(o=>o.name!==n&&(o.ticket===void 0||o.ticket<s||o.ticket===s&&(o.pid<process.pid||o.pid===process.pid&&o.name.localeCompare(n)<0)));if(i)throw new Error("Another Alran update is already running.")}catch(s){B(t,{force:true});throw s}let a=false;return()=>{if(a)return;a=true;B(t,{force:true})}}function Ie(r,e=process.platform){const n=E(e);const t=n.join(r.activePrefix,D);const a=Le(r.stagingPrefix,r,e);tr(r.stagingPrefix,a,r.runtimeExecutable,e);we(r.stagingPrefix,r,e);M(t,{recursive:true,mode:448});let s=r.expectedVersion;let i=n.join(t,s);if(O(i)){s=`${r.expectedVersion}-repair-${N()}`;i=n.join(t,s)}be(r.stagingPrefix,i);we(i,r,e);sr(r,e);if(!ir(r.activePrefix,e)){ar(r.activePrefix,e)}w(n.join(r.activePrefix,Re),`${s}
|
|
5
|
+
`,384);return i}function Le(r,e,n){const t=$(r,e.packageName,n);if(t.version!==e.expectedVersion){throw new Error(`Alran release contains ${t.version}; expected ${e.expectedVersion}.`)}return t}function we(r,e,n){const t=Le(r,e,n);const a=Te(r,t,e.runtimeExecutable,n);for(const[s,i]of a){if(J(s,"utf8")!==i){throw new Error(`Alran release launcher is invalid: ${s}`)}}}function tr(r,e,n,t){for(const[a,s]of Te(r,e,n,t)){w(a,s,448)}}function Te(r,e,n,t){const a=E(t);const s=new Map;if(!O(n)){throw new Error("Alran versioned launcher runtime is missing.")}for(const i of _(e)){if(!i.binEntry){throw new Error(`Alran versioned ${i.name} package entry is missing.`)}const o=a.join(e.packageRoot,...i.binEntry.split("/"));const l=a.relative(r,o);if(!l||l.startsWith("..")||a.isAbsolute(l)||!O(o)){throw new Error(`Alran versioned ${i.name} launcher path is invalid.`)}if(t==="win32"){s.set(a.join(r,`${i.releaseLauncher}.cmd`),`@ECHO off\r
|
|
6
|
+
"${Se(n)}" "%~dp0${Se(l)}" %*\r
|
|
7
|
+
EXIT /B %ERRORLEVEL%\r
|
|
8
|
+
`);s.set(a.join(r,`${i.releaseLauncher}.ps1`),`#!/usr/bin/env pwsh\r
|
|
9
|
+
& '${Ve(n)}' (Join-Path $PSScriptRoot '${Ve(l)}') @args\r
|
|
10
|
+
exit $LASTEXITCODE\r
|
|
11
|
+
`);continue}s.set(a.join(r,i.releaseLauncher),`#!/bin/sh
|
|
12
|
+
set -eu
|
|
13
|
+
root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
|
|
14
|
+
node=${lr(n)}
|
|
15
|
+
if [ ! -x "$node" ]; then
|
|
16
|
+
printf "%s\\n" "Alran: Node runtime is missing: $node" "Alran: a system upgrade such as brew upgrade may have removed it." "Alran: re-run the Alran installer to repair this installation." >&2
|
|
17
|
+
exit 127
|
|
18
|
+
fi
|
|
19
|
+
exec "$node" "$root/${cr(l)}" "$@"
|
|
20
|
+
`)}return s}function ar(r,e){for(const[n,t]of Ce(r,e)){w(n,t,448)}}function ir(r,e){try{for(const[n,t]of Ce(r,e)){if(J(n,"utf8")!==t)return false}return true}catch{return false}}function Ce(r,e){const n=E(e);const t=new Map;if(e==="win32"){for(const a of _()){t.set(n.join(r,`${a.name}.cmd`),`@ECHO off\r
|
|
21
|
+
SETLOCAL\r
|
|
22
|
+
SET /P ALRAN_RELEASE=<"%~dp0current"\r
|
|
23
|
+
ECHO(%ALRAN_RELEASE%| %SystemRoot%\\System32\\findstr.exe /R /X "[0-9A-Za-z][0-9A-Za-z._-]*" >NUL || EXIT /B 1\r
|
|
24
|
+
CALL "%~dp0releases\\%ALRAN_RELEASE%\\${a.releaseLauncher}.cmd" %*\r
|
|
25
|
+
EXIT /B %ERRORLEVEL%\r
|
|
26
|
+
`);t.set(n.join(r,`${a.name}.ps1`),`#!/usr/bin/env pwsh\r
|
|
27
|
+
$release = (Get-Content -LiteralPath (Join-Path $PSScriptRoot 'current') -Raw).Trim()\r
|
|
28
|
+
if ($release -notmatch '^[0-9A-Za-z][0-9A-Za-z._-]*$') { throw 'Invalid Alran current release pointer.' }\r
|
|
29
|
+
& (Join-Path $PSScriptRoot "releases\\$release\\${a.releaseLauncher}.ps1") @args\r
|
|
30
|
+
exit $LASTEXITCODE\r
|
|
31
|
+
`)}return t}for(const a of _()){t.set(n.join(r,"bin",a.name),`#!/bin/sh
|
|
32
|
+
set -eu
|
|
33
|
+
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P)
|
|
34
|
+
release=$(tr -d "\\r\\n" < "$root/current")
|
|
35
|
+
case "$release" in ""|*[!0-9A-Za-z._-]*) echo "Invalid Alran current release pointer." >&2; exit 1;; esac
|
|
36
|
+
exec "$root/releases/$release/${a.releaseLauncher}" "$@"
|
|
37
|
+
`)}return t}function _(r){return[{name:"alran",releaseLauncher:".alran-launcher",...r?{binEntry:r.binEntry}:{}},{name:"alran-tools",releaseLauncher:".alran-tools-launcher",...r?{binEntry:r.alranToolsBinEntry}:{}}]}function sr(r,e){const n=E(e);const t={schemaVersion:2,product:"alran-code",updateOwner:"npm-prefix",packageManager:"npm",packageName:r.packageName,registry:new URL(r.registry).href,distTag:"latest",npmExecutable:r.npmExecutable,nodeExecutable:r.runtimeExecutable,prefix:r.activePrefix,layoutVersion:nr,releasesDirectory:D,currentFile:Re};w(n.join(r.activePrefix,"install.json"),`${JSON.stringify(t,null,2)}
|
|
38
|
+
`,384)}function w(r,e,n){const t=`${r}.tmp-${process.pid}-${N()}`;M(P.dirname(r),{recursive:true,mode:448});try{$e(t,e,{mode:n});qe(t,n);be(t,r)}catch(a){B(t,{force:true});throw a}}function Ee(r){const e=[];for(const n of er(r)){const t=/^(\d+)-.+\.claim$/u.exec(n);if(!t)continue;const a=Number(t[1]);if(!Number.isSafeInteger(a)||a<=0||!or(a))continue;try{const s=J(P.join(r,n),"utf8").trim();const i=/^\d+$/u.test(s)?Number(s):void 0;e.push({name:n,pid:a,...i&&Number.isSafeInteger(i)?{ticket:i}:{}})}catch{}}return e}function or(r){try{process.kill(r,0);return true}catch(e){return e.code==="EPERM"}}function E(r){return r==="win32"?P.win32:P.posix}function lr(r){return`'${r.replaceAll("'",`'"'"'`)}'`}function cr(r){return r.replaceAll("\\","/").replaceAll('"','\\"').replaceAll("$","\\$").replaceAll("`","\\`")}function Se(r){return r.replaceAll("%","%%")}function Ve(r){return r.replaceAll("'","''")}var Oe=class{currentVersion;packageTag;distribution;platform;prefixInstall;entryFile;runtimeExecutable;environment;dependencies;constructor(e,n={}){this.currentVersion=e.currentVersion;const t=e.environment??process.env;const a=e.installRoot??C(t);const s=e.platform??process.platform;this.platform=s;this.environment=t;this.entryFile=e.entryFile??process.argv[1];this.prefixInstall=e.prefixInstall??ee(this.entryFile,s);this.runtimeExecutable=e.runtimeExecutable??this.prefixInstall?.nodeExecutable??process.execPath;const i=this.prefixInstall?W(t,this.runtimeExecutable,s):t;this.packageTag=e.packageTag??G();this.distribution=b(e.packageName,this.prefixInstall?.registry);this.dependencies={detectInstallSource:n.detectInstallSource??(()=>X({installRoot:a,platform:s,prefixInstall:()=>this.prefixInstall})),createManagedService:n.createManagedService??(()=>new R({currentVersion:e.currentVersion,installRoot:a,environment:t})),resolveLatestPackageVersion:n.resolveLatestPackageVersion??(o=>Y(o,{platform:s,distribution:this.distribution,environment:i,...this.prefixInstall?{npmExecutable:this.prefixInstall.executable,runtimeExecutable:this.runtimeExecutable}:{}})),runPackageManager:n.runPackageManager??((o,l)=>Q(this.prefixInstall?Z(o,this.runtimeExecutable):o,i,l)),readInstalledPackageVersion:n.readInstalledPackageVersion??q,readPrefixPackageMetadata:n.readPrefixPackageMetadata??((o,l)=>$(o,l,s)),validatePrefixPackage:n.validatePrefixPackage??((o,l,f)=>ne(o,l,this.runtimeExecutable,f)),countPrefixUpdateBlockers:n.countPrefixUpdateBlockers??ae,removePrefixStaging:n.removePrefixStaging??te,createVersionedPrefixStaging:n.createVersionedPrefixStaging??((o,l)=>Ne(o,l,s)),prepareVersionedPrefixStaging:n.prepareVersionedPrefixStaging??Me,activateVersionedPrefix:n.activateVersionedPrefix??(o=>Ie(o,s)),acquirePrefixUpdateLock:n.acquirePrefixUpdateLock??Ue}}async inspect(){const e=await this.dependencies.detectInstallSource();if(e==="managed-installer"){const i=await this.dependencies.createManagedService().check();return{kind:i.status,source:e,currentVersion:i.currentVersion,latestVersion:i.latestVersion,channel:i.channel}}if(e==="unsupported"){return{kind:"manual",source:e,currentVersion:this.currentVersion,command:x("npm-global",this.packageTag,this.platform,this.distribution).display}}if(H(this.distribution.packageName)){return{kind:"manual",source:"unsupported",currentVersion:this.currentVersion,command:`npm uninstall --global ${this.distribution.packageName} && npm install --global ${z}`}}const n=e==="npm-prefix"?L(this.entryFile):void 0;if(n){const i=n.activation.expectedVersion;return{kind:"package-manager",source:e,currentVersion:this.currentVersion,latestVersion:i,packageTag:this.packageTag,command:x(e,i,this.platform,this.distribution,this.prefixInstall)}}const t=await this.dependencies.resolveLatestPackageVersion(this.packageTag);const a=V(this.currentVersion,t);const s=this.packageTag!=="latest";if(a===0){return{kind:"current",source:e,currentVersion:this.currentVersion,latestVersion:t,packageTag:this.packageTag}}if(a>0&&!s){return{kind:"ahead",source:e,currentVersion:this.currentVersion,latestVersion:t,packageTag:this.packageTag}}return{kind:"package-manager",source:e,currentVersion:this.currentVersion,latestVersion:t,packageTag:this.packageTag,command:x(e,t,this.platform,this.distribution,this.prefixInstall)}}async apply(e,n={}){if(e.kind==="manual"||e.kind==="current"||e.kind==="ahead"){throw new Error(`Alran update plan ${e.kind} cannot be applied automatically.`)}if(e.kind==="available"){const a=await this.dependencies.createManagedService().apply({channel:e.channel,version:e.latestVersion,...n});return a.applied?{applied:true,message:`Alran ${a.latestVersion} is installed. Restart running Alran sessions to use it.`}:{applied:false,message:`Alran ${a.currentVersion} is already active.`}}if(e.source==="npm-prefix"){return this.applyNpmPrefixUpdate(e,n)}p(n,"installing",false);await this.dependencies.runPackageManager(e.command,n);const t=this.dependencies.readInstalledPackageVersion();if(t!==e.latestVersion){throw new Error(`Alran update installed ${t||"<unknown>"}; expected ${e.latestVersion}.`)}p(n,"completed",false);return{applied:true,message:`Alran ${e.latestVersion} was installed through ${pr(e.source)}. Restart Alran to use the installed version.`}}async applyNpmPrefixUpdate(e,n){if(e.source!=="npm-prefix"){throw new Error(he(this.environment))}const t=this.prefixInstall;if(!t){throw new Error(Ae(this.environment))}const a=L(this.entryFile);if(a){const o=this.dependencies.countPrefixUpdateBlockers(a.activation.activePrefix);return{applied:false,restartRequired:true,message:a.state==="activated"?xe(a.activation.expectedVersion,{blockingSessionCount:o,environment:this.environment}):Pe(a.activation.expectedVersion,{blockingSessionCount:o,environment:this.environment})}}const s=this.dependencies.acquirePrefixUpdateLock(t.prefix);let i;try{i=this.dependencies.createVersionedPrefixStaging(t.prefix,e.latestVersion);const o=x("npm-prefix",e.latestVersion,this.platform,this.distribution,{...t,prefix:i});p(n,"staging",true);this.dependencies.prepareVersionedPrefixStaging(i);p(n,"installing",false);await this.dependencies.runPackageManager(o,n);p(n,"validating",false);const l=this.dependencies.readPrefixPackageMetadata(i,t.packageName);if(l.version!==e.latestVersion){throw new Error(ye(l.version,e.latestVersion,this.environment))}await this.dependencies.validatePrefixPackage(i,l,e.latestVersion);p(n,"activating",false);this.dependencies.activateVersionedPrefix({stagingPrefix:i,activePrefix:t.prefix,packageName:t.packageName,expectedVersion:e.latestVersion,runtimeExecutable:this.runtimeExecutable,npmExecutable:t.executable,registry:t.registry});p(n,"completed",false);return{applied:true,restartRequired:false,message:ve(e.latestVersion,this.environment)}}catch(o){if(i)this.dependencies.removePrefixStaging(i);throw new Error(ke(e.latestVersion,dr(o),this.environment),{cause:o})}finally{s()}}};function dr(r){return r instanceof Error?r.message:String(r)}function pr(r){if(r==="npm-prefix")return"npm";return r.replace("-global","")}export{Sr as a,Vr as b,Oe as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
var d={maxCodeBytes:64*1024,maxHeapBytes:64*1024*1024,maxComputeMs:1e3,maxWallClockMs:12e4,shutdownGraceMs:5e3,maxToolCalls:100,maxConcurrentToolCalls:16,maxBridgeMessageBytes:16*1024*1024,maxBridgeResultBytes:32*1024*1024,maxOuterResultBytes:64*1024,maxConsoleBytes:16*1024};var i="PTC_TOOL_CALL_LIMIT_EXCEEDED";var l="PTC_RESULT_TOO_LARGE";function c(e,t,r){return{status:"failed",isError:true,data:{},truncation:{truncated:"unknown"},error:{code:l,message:`PTC child result is ${t} bytes, over the ${r}-byte per-call limit, so it was not delivered; the tool itself ran. Narrow the arguments and retry.`,toolCallId:e}}}function g(e,t,r,o){return{...c(e,t,o),error:{code:l,message:`PTC child result is ${t} bytes; with ${r} bytes of earlier results the program has not taken yet, the total would exceed the ${o}-byte limit, so it was not delivered; the tool itself ran. Run fewer large calls in parallel or read in smaller batches, then retry.`,toolCallId:e}}}function p(e,t){return{status:"failed",isError:true,data:{},truncation:{truncated:"unknown"},error:{code:i,message:`PTC refused this call after reaching the ${t}-call limit; it was not executed.`,toolCallId:e}}}function P(e={}){return{...d,...e}}function u(e){return new TextEncoder().encode(e).byteLength}function C(e){const t=JSON.parse(e);if(!s(t)||!a(t)){throw new Error("Tool arguments must be a JSON object with safe property names.")}return t}function f(e,t){if(!y(e))throw new n("invalid_tool_result","Value is not JSON-serializable.");const r=JSON.stringify(e);if(r===void 0)throw new n("invalid_tool_result","Value is not JSON-serializable.");const o=u(r);if(o>t){throw new n("bridge_limit_exceeded",`Serialized value exceeds the ${t}-byte PTC transport limit.`,o)}return r}var n=class extends Error{constructor(r,o,m){super(o);this.code=r;this.bytes=m;this.name="PtcSerializationError"}code;bytes};function y(e){return a(e)}function a(e,t=0){if(t>100)return false;if(e===null||typeof e==="string"||typeof e==="boolean")return true;if(typeof e==="number")return Number.isFinite(e);if(Array.isArray(e))return Array.from(e).every(r=>a(r,t+1));if(!s(e))return false;return Object.entries(e).every(([r,o])=>r!=="__proto__"&&r!=="constructor"&&r!=="prototype"&&a(o,t+1))}function s(e){if(!e||typeof e!=="object"||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}export{d as a,l as b,c,g as d,p as e,P as f,C as g,f as h,n as i,y as j};
|