@uniqbit/mate-core 0.18.5 → 1.0.0-canary.2
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/claude-capability-plugins/companion-mentions/.claude-plugin/marketplace.json +14 -0
- package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +8 -0
- package/claude-capability-plugins/companion-mentions/hooks/companion.ts +457 -0
- package/claude-capability-plugins/companion-mentions/hooks/hooks.json +1 -0
- package/claude-capability-plugins/companion-mentions/hooks/register.ts +403 -0
- package/claude-plugin/hooks/companion-instructions.mjs +9 -0
- package/claude-plugin/hooks/hooks.json +21 -2
- package/claude-plugin/hooks/tokensave-route.mjs +52 -0
- package/opencode-plugin/src/server.ts +4 -0
- package/opencode-plugin/src/tui.tsx +2 -0
- package/opencode-plugin/tui.tsx +2 -0
- package/package.json +52 -15
- package/src/brand/art.generated.ts +69 -0
- package/src/brand/index.ts +12 -0
- package/src/brand/palette.ts +19 -0
- package/src/brand/svg.generated.ts +8 -0
- package/src/brand/terminal.ts +88 -0
- package/src/brand/types.ts +33 -0
- package/src/cli/commands/artifact/apply-context.ts +275 -0
- package/src/cli/commands/artifact/artifact.ts +12 -0
- package/src/cli/commands/artifact/delivery/archive.ts +125 -0
- package/src/cli/commands/artifact/delivery/branch-flags.ts +55 -0
- package/src/cli/commands/artifact/delivery/environment.ts +127 -0
- package/src/cli/commands/artifact/delivery/link.ts +174 -0
- package/src/cli/commands/artifact/delivery/output.ts +89 -0
- package/src/cli/commands/artifact/finish/command.ts +83 -8
- package/src/cli/commands/artifact/finish/engine.ts +91 -14
- package/src/cli/commands/artifact/finish/finisher.ts +10 -0
- package/src/cli/commands/artifact/finish/git.ts +132 -19
- package/src/cli/commands/artifact/finish/openspec.ts +182 -138
- package/src/cli/commands/artifact/finish/secret-scan.ts +43 -0
- package/src/cli/commands/artifact/finish/worktree-cleanup.ts +92 -0
- package/src/cli/commands/artifact/pending/command.ts +31 -3
- package/src/cli/commands/artifact/pending/discovery.ts +21 -57
- package/src/cli/commands/cap/graphify.ts +52 -3
- package/src/cli/commands/cap/index-cmd.ts +71 -15
- package/src/cli/commands/cap/openspec.ts +13 -25
- package/src/cli/commands/cap/tokensave.ts +7 -5
- package/src/cli/commands/companion/link.ts +14 -1
- package/src/cli/commands/companion/open.ts +68 -46
- package/src/cli/commands/companion/sync.ts +10 -0
- package/src/cli/commands/companion/tui.ts +17 -7
- package/src/cli/commands/companion/update.ts +143 -48
- package/src/cli/commands/doctor.ts +195 -7
- package/src/cli/commands/factory/factory.ts +301 -0
- package/src/cli/commands/install.ts +133 -9
- package/src/cli/commands/launch/shared.ts +16 -11
- package/src/cli/commands/plugin/install.ts +9 -4
- package/src/cli/commands/plugin/plugin.ts +3 -2
- package/src/cli/commands/report/adapter.ts +11 -2
- package/src/cli/commands/report/contract.ts +21 -0
- package/src/cli/commands/report/highlight.ts +34 -4
- package/src/cli/commands/report/index.ts +20 -1
- package/src/cli/commands/report/markdown.ts +110 -0
- package/src/cli/commands/report/palette.ts +118 -0
- package/src/cli/commands/report/renderer.ts +456 -153
- package/src/cli/commands/report/types.ts +16 -0
- package/src/cli/commands/session/context.ts +102 -0
- package/src/cli/commands/setup.ts +50 -24
- package/src/cli/commands/studio/factory-credential.ts +49 -0
- package/src/cli/commands/studio/index.ts +29 -2
- package/src/cli/commands/studio/openspec-cli.ts +10 -58
- package/src/cli/commands/studio/payload.ts +249 -15
- package/src/cli/commands/studio/routes.ts +41 -6
- package/src/cli/commands/studio/selection.ts +161 -17
- package/src/cli/commands/studio/server.ts +404 -324
- package/src/cli/commands/studio/services.ts +60 -0
- package/src/cli/commands/studio/studio-app.ts +67 -0
- package/src/cli/commands/studio/terminal-assets.ts +21 -33
- package/src/cli/commands/studio/terminal.ts +85 -15
- package/src/cli/commands/studio/views/model.ts +18 -0
- package/src/cli/commands/studio/views/vault/markdown-tree.ts +267 -0
- package/src/cli/commands/studio/views/vault/view.ts +185 -0
- package/src/cli/commands/studio/workset-session.ts +131 -0
- package/src/cli/commands/unwrap.ts +8 -0
- package/src/cli/commands/update.ts +27 -1
- package/src/cli/commands/working/cleanup.ts +10 -1
- package/src/cli/commands/working/link.ts +76 -0
- package/src/cli/commands/working/working.ts +10 -0
- package/src/cli/commands/working/worktree.ts +356 -0
- package/src/cli/commands/wrap.ts +5 -13
- package/src/cli/companion-link-wizard.tsx +2 -0
- package/src/cli/companion-selector.tsx +2 -0
- package/src/cli/confirm.ts +2 -0
- package/src/cli/install-plan.tsx +127 -160
- package/src/cli/launch-selector.tsx +2 -0
- package/src/cli/main.ts +22 -1
- package/src/cli/parse-flags.ts +32 -6
- package/src/cli/repo-list-table.tsx +2 -0
- package/src/cli/setup-selector.tsx +86 -151
- package/src/cli/usage.ts +14 -0
- package/src/create-mate.ts +5 -4
- package/src/hooks/companion-instructions.ts +190 -0
- package/src/hooks/hook-io.ts +63 -0
- package/src/hooks/session-banner.ts +21 -29
- package/src/hooks/session-guidance.ts +9 -17
- package/src/hooks/session-prepare.ts +115 -28
- package/src/hooks/tokensave-route.ts +26 -0
- package/src/hooks/validate-artifact-path.ts +82 -24
- package/src/index.ts +4 -0
- package/src/lib/apply-context/fingerprint.ts +174 -0
- package/src/lib/apply-context/protocol.ts +193 -0
- package/src/lib/change-layout.ts +154 -0
- package/src/lib/components/confirm-prompt.tsx +21 -9
- package/src/lib/components/select-menu.tsx +10 -3
- package/src/lib/components/spinner.tsx +4 -2
- package/src/lib/components/startup-progress.tsx +227 -41
- package/src/lib/components/text-input-display.tsx +2 -0
- package/src/lib/components/wizard-footer.tsx +2 -0
- package/src/lib/components/wizard-header.tsx +16 -12
- package/src/lib/context-mode-package.ts +24 -11
- package/src/lib/delivery/archive-change.ts +166 -0
- package/src/lib/delivery/branches.ts +132 -0
- package/src/lib/delivery/environment.ts +35 -0
- package/src/lib/delivery/forge.ts +279 -0
- package/src/lib/delivery/merge-git.ts +261 -0
- package/src/lib/delivery/overlap.ts +209 -0
- package/src/lib/delivery/record-delivery.ts +283 -0
- package/src/lib/delivery/record.ts +403 -0
- package/src/lib/delivery/refresh.ts +268 -0
- package/src/lib/delivery/repository-access.ts +141 -0
- package/src/lib/delivery/resolve-branch.ts +162 -0
- package/src/lib/delivery/stages.ts +111 -0
- package/src/lib/delivery/token.ts +24 -0
- package/src/lib/factory/attach-client.ts +113 -0
- package/src/lib/factory/attach.ts +178 -0
- package/src/lib/factory/broker.ts +190 -0
- package/src/lib/factory/bun-commands.ts +39 -0
- package/src/lib/factory/client.ts +92 -0
- package/src/lib/factory/command.ts +61 -0
- package/src/lib/factory/credential-store.ts +153 -0
- package/src/lib/factory/frames.ts +77 -0
- package/src/lib/factory/ids.ts +58 -0
- package/src/lib/factory/keyed-serial.ts +27 -0
- package/src/lib/factory/outcomes/actions.ts +114 -0
- package/src/lib/factory/outcomes/index.ts +381 -0
- package/src/lib/factory/outcomes/lifecycle.ts +205 -0
- package/src/lib/factory/outcomes/runs.ts +81 -0
- package/src/lib/factory/outcomes/sessions.ts +38 -0
- package/src/lib/factory/prepare.ts +49 -0
- package/src/lib/factory/pty.ts +103 -0
- package/src/lib/factory/runner/companion-context.ts +178 -0
- package/src/lib/factory/runner/control.ts +92 -0
- package/src/lib/factory/runner/harness-agent.ts +250 -0
- package/src/lib/factory/runner/live.ts +159 -0
- package/src/lib/factory/runner/questions.ts +22 -0
- package/src/lib/factory/runner/rank.ts +26 -0
- package/src/lib/factory/runner/run-policy.ts +12 -0
- package/src/lib/factory/runner/run.ts +199 -0
- package/src/lib/factory/runner/scheduler.ts +416 -0
- package/src/lib/factory/runner/state.ts +233 -0
- package/src/lib/factory/runner/workflow.ts +542 -0
- package/src/lib/factory/runtime.ts +972 -0
- package/src/lib/factory/sandbox.ts +292 -0
- package/src/lib/factory/worktree-branch.ts +17 -0
- package/src/lib/frontmatter.ts +18 -0
- package/src/lib/install.ts +66 -14
- package/src/lib/live-progress.ts +36 -0
- package/src/lib/member-choices.ts +67 -0
- package/src/lib/opencode-plugin-package.ts +5 -5
- package/src/lib/openspec-cli.ts +116 -0
- package/src/lib/openspec-scopes.ts +86 -0
- package/src/lib/orchestrator/adapters/base.ts +55 -22
- package/src/lib/orchestrator/adapters/claude-args.ts +50 -0
- package/src/lib/orchestrator/adapters/claude.ts +54 -41
- package/src/lib/orchestrator/adapters/opencode.ts +2 -0
- package/src/lib/orchestrator/config-store.ts +3 -2
- package/src/lib/orchestrator/editor.ts +31 -25
- package/src/lib/orchestrator/openspec-store.ts +14 -54
- package/src/lib/orchestrator/projection-claude-commands.ts +36 -0
- package/src/lib/orchestrator/projection-claude-links.ts +159 -0
- package/src/lib/orchestrator/projection-claude-skills.ts +19 -137
- package/src/lib/orchestrator/projection-entries.ts +100 -34
- package/src/lib/orchestrator/projection-opencode-copies.ts +32 -15
- package/src/lib/orchestrator/projection-openspec-store.ts +54 -9
- package/src/lib/orchestrator/projection-runtime-documents.ts +15 -6
- package/src/lib/orchestrator/projection-types.ts +36 -1
- package/src/lib/orchestrator/refresh-working-claude-links.ts +87 -0
- package/src/lib/orchestrator/session-context-link.ts +67 -0
- package/src/lib/orchestrator/session-prepare.ts +45 -5
- package/src/lib/orchestrator/setup-compatibilities.ts +56 -70
- package/src/lib/orchestrator/types.ts +7 -2
- package/src/lib/orchestrator/working-repo-projection.ts +50 -7
- package/src/lib/orchestrator/workspace-document.ts +105 -0
- package/src/lib/orchestrator/wrap-pass.ts +22 -1
- package/src/lib/package-paths.ts +37 -0
- package/src/lib/runtime-directory-refresh.ts +17 -1
- package/src/lib/workset/record.ts +513 -0
- package/src/lib/workset/repositories.ts +55 -0
- package/src/lib/workset/stage.ts +148 -0
- package/src/lib/workset/stages.ts +113 -0
- package/src/lib/workset/worktree-index.ts +116 -0
- package/src/lib/workset/worktree.ts +830 -0
- package/src/opencode/companion-hooks.ts +109 -7
- package/src/opencode/companion-policy.ts +37 -18
- package/src/opencode/enter-worktree.ts +72 -0
- package/src/opencode/projected-guidance.ts +4 -1
- package/src/opencode/session-prepare.ts +2 -1
- package/src/opencode/tui.tsx +13 -6
- package/src/plugins.ts +1 -0
- package/src/runtime/artifact-refusal.ts +63 -0
- package/src/runtime/claude-delivery-plan.ts +107 -8
- package/src/runtime/commit-attribution-guard.ts +181 -0
- package/src/runtime/companion-git.ts +52 -10
- package/src/runtime/companion-guidance.ts +20 -8
- package/src/runtime/companion-instructions.ts +340 -0
- package/src/runtime/companion-lock.ts +30 -7
- package/src/runtime/env.ts +48 -3
- package/src/runtime/error-message.ts +4 -0
- package/src/runtime/git-layout.ts +219 -0
- package/src/runtime/index.ts +29 -0
- package/src/runtime/managed-block.ts +117 -0
- package/src/runtime/markdown-scan.ts +266 -0
- package/src/runtime/physical-path.ts +111 -0
- package/src/runtime/policy.ts +50 -2
- package/src/runtime/projected-flag.ts +7 -0
- package/src/runtime/projected-guidance.ts +1 -0
- package/src/runtime/runtime-directory.ts +5 -0
- package/src/runtime/runtime-document-manifest.ts +62 -11
- package/src/runtime/secret-guard.ts +162 -0
- package/src/runtime/secret-patterns.ts +397 -0
- package/src/runtime/secret-scan.ts +90 -0
- package/src/runtime/session-context.ts +98 -0
- package/src/runtime/session-kind.ts +13 -0
- package/src/runtime/shell-heredoc.ts +81 -0
- package/src/runtime/tokensave-route.ts +152 -0
- package/src/runtime/wrap-state.ts +44 -2
- package/src/runtime/write-atomic.ts +64 -0
- package/src/studio.ts +124 -0
- package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +14 -10
- package/src/templates/capabilities/openspec-cap/mate-minimal/templates/spec.md +3 -5
- package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +18 -102
- package/src/templates/capabilities/openspec-cap/mate-v1/templates/spec.md +3 -5
- package/src/templates/capabilities/openspec-cap/openspec-conventions.yaml +20 -14
- package/src/templates/mate-skills/THIRD-PARTY-NOTICES.md +40 -0
- package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +134 -0
- package/src/templates/mate-skills/agents/mate-apply-change/references/mate-compact-apply.md +47 -0
- package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +200 -0
- package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +86 -0
- package/src/templates/mate-skills/{claude/mate-openspec-backfill → agents/mate-backfill-spec}/SKILL.md +11 -4
- package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +110 -0
- package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +66 -0
- package/src/templates/mate-skills/agents/mate-explore-change/references/openspec-explore.md +350 -0
- package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +11 -4
- package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +2 -2
- package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +12 -5
- package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +108 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +47 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-propose.md +169 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +103 -0
- package/src/templates/mate-skills/agents/{mate-artifact-publish → mate-publish-artifact}/SKILL.md +111 -24
- package/src/templates/mate-skills/{claude/mate-artifact-publish → agents/mate-publish-artifact}/references/openspec.md +8 -5
- package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +95 -16
- package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +87 -68
- package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +134 -0
- package/src/templates/mate-skills/claude/mate-apply-change/references/mate-compact-apply.md +47 -0
- package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +200 -0
- package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +86 -0
- package/src/templates/mate-skills/{agents/mate-openspec-backfill → claude/mate-backfill-spec}/SKILL.md +11 -4
- package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +110 -0
- package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +66 -0
- package/src/templates/mate-skills/claude/mate-explore-change/references/openspec-explore.md +350 -0
- package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +11 -4
- package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +2 -2
- package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +12 -5
- package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +108 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +47 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-propose.md +169 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +103 -0
- package/src/templates/mate-skills/claude/{mate-artifact-publish → mate-publish-artifact}/SKILL.md +111 -24
- package/src/templates/mate-skills/{agents/mate-artifact-publish → claude/mate-publish-artifact}/references/openspec.md +8 -5
- package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +95 -16
- package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +87 -68
- package/src/templates/mate-skills/openspec-references.ts +142 -0
- package/src/templates/root/TEMPLATE_AGENTS.md +2 -2
- package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +3938 -391
- package/src/tools/setup/capabilities/companion-mentions.ts +27 -0
- package/src/tools/setup/capabilities/context-mode.ts +56 -7
- package/src/tools/setup/capabilities/graphify-gate.ts +31 -0
- package/src/tools/setup/capabilities/graphify-secrets.ts +243 -0
- package/src/tools/setup/capabilities/graphify.ts +46 -7
- package/src/tools/setup/capabilities/openspec.ts +163 -272
- package/src/tools/setup/capabilities/react-doctor.ts +8 -1
- package/src/tools/setup/capabilities/rtk.ts +4 -0
- package/src/tools/setup/capabilities/tokensave.ts +113 -71
- package/src/tools/setup/context-services.ts +9 -17
- package/src/tools/setup/dynamic-plugins/install.ts +24 -28
- package/src/tools/setup/engine.ts +100 -23
- package/src/tools/setup/install-contract.ts +8 -0
- package/src/tools/setup/managed-output.ts +51 -0
- package/src/tools/setup/mate-skill-copies.ts +51 -0
- package/src/tools/setup/mate.ts +86 -11
- package/src/tools/setup/package-managers/uv.ts +73 -11
- package/src/tools/setup/plugin.ts +40 -0
- package/src/tools/setup/plugins/guidance.ts +7 -4
- package/src/tools/setup/providers/agent-file-sections.ts +4 -2
- package/src/tools/setup/providers/claude-attribution.ts +65 -0
- package/src/tools/setup/providers/claude-plugin-folders.ts +625 -0
- package/src/tools/setup/providers/claude-plugin-hooks.ts +51 -19
- package/src/tools/setup/providers/claude-worktree-plugins.ts +122 -0
- package/src/tools/setup/providers/claude.ts +290 -8
- package/src/tools/setup/providers/opencode.ts +180 -1
- package/src/tools/setup/utils.ts +18 -4
- package/src/tools/setup/working-repo-cleanup.ts +29 -1
- package/src/tools/setup/working-repo-local-state.ts +252 -75
- package/src/tools/setup.ts +183 -26
- package/studio-dist/client/assets/companion-view-Csva26Ir.js +1 -0
- package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +1 -0
- package/studio-dist/client/assets/dist-Dm7MtyHc.js +5 -0
- package/studio-dist/client/assets/factory-B7l9ZQyx.js +4 -0
- package/studio-dist/client/assets/index-n6uo_92S.js +40 -0
- package/studio-dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
- package/studio-dist/client/assets/prepaint-CD5OpmTM.js +24 -0
- package/studio-dist/client/assets/queries-CN3JwMBX.js +1 -0
- package/studio-dist/client/assets/react-CabXf2Ds.js +1 -0
- package/studio-dist/client/assets/report-time-Dc-KOqQu.js +1 -0
- package/studio-dist/client/assets/reports-C01RsnMA.js +1 -0
- package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +1 -0
- package/studio-dist/client/assets/routes-4pbC-2Hj.js +1 -0
- package/studio-dist/client/assets/skills-CihQganl.js +1 -0
- package/studio-dist/client/assets/spec-areas-C2L48N4C.js +1 -0
- package/studio-dist/client/assets/specs-D24_35_K.js +1 -0
- package/studio-dist/client/assets/studio-DKxfi691.css +1 -0
- package/studio-dist/client/assets/studio-queries-rvbJupCy.js +3 -0
- package/studio-dist/client/assets/terminal-eU5fzQzv.css +1 -0
- package/studio-dist/client/assets/vault-Bd4CQiTK.js +1 -0
- package/studio-dist/client/assets/warnings-V_Ys51wJ.js +1 -0
- package/studio-dist/client/assets/wasm-inline-C2en61B5.js +1 -0
- package/studio-dist/client/assets/workflow-BJejeVwQ.js +1 -0
- package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-BQKuMdJW.js +3881 -0
- package/studio-dist/server/assets/_tanstack-start-manifest_v.js +85 -0
- package/studio-dist/server/assets/actions-Bvgj9eb8.js +54 -0
- package/studio-dist/server/assets/actions-D8erOphH.js +44 -0
- package/studio-dist/server/assets/companion-view-aBady57v.js +33 -0
- package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +459 -0
- package/studio-dist/server/assets/createServerRpc-tK2lE9R2.js +11 -0
- package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +778 -0
- package/studio-dist/server/assets/dist-DpJWKyCm.js +5582 -0
- package/studio-dist/server/assets/empty-plugin-adapters-Cipd4ZH4.js +4 -0
- package/studio-dist/server/assets/factory-D6xnjedJ.js +2385 -0
- package/studio-dist/server/assets/factory-DT3UzHlh.js +68 -0
- package/studio-dist/server/assets/model-PyPALjii.js +18 -0
- package/studio-dist/server/assets/prepaint-BMke0fo1.js +41 -0
- package/studio-dist/server/assets/queries-Ag2iL8q2.js +107 -0
- package/studio-dist/server/assets/react-COs0LHn-.js +51 -0
- package/studio-dist/server/assets/report-time-DAfzln-N.js +8 -0
- package/studio-dist/server/assets/reports-BnUNJVtx.js +126 -0
- package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +34 -0
- package/studio-dist/server/assets/router-BH--drIx.js +4298 -0
- package/studio-dist/server/assets/routes-khSDK1bV.js +361 -0
- package/studio-dist/server/assets/search-JAKurDNh.js +36 -0
- package/studio-dist/server/assets/shell-CboT2f66.js +51 -0
- package/studio-dist/server/assets/skills-MWYnWoKs.js +106 -0
- package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +16 -0
- package/studio-dist/server/assets/specs-DE3w8hZP.js +155 -0
- package/studio-dist/server/assets/start-BW5ovN0k.js +33 -0
- package/studio-dist/server/assets/studio-BeltxxKt.js +216 -0
- package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +3365 -0
- package/studio-dist/server/assets/utils-C9CX1kcy.js +221 -0
- package/studio-dist/server/assets/vault-BGulVoNh.js +70 -0
- package/studio-dist/server/assets/vault-CuyyhLyB.js +832 -0
- package/studio-dist/server/assets/views-Bd7cRr27.js +82 -0
- package/studio-dist/server/assets/warnings-BH05rOuG.js +15 -0
- package/studio-dist/server/assets/wasm-inline-CNeBKGwC.js +3 -0
- package/studio-dist/server/assets/workflow-BSuIKWqH.js +42 -0
- package/studio-dist/server/server.js +16220 -0
- package/wrappers/bin/graphify +52 -4
- package/wrappers/bin/openspec +33 -9
- package/wrappers/lib/graphify-gate.mjs +8 -0
- package/src/cli/commands/studio/views/client.ts +0 -654
- package/src/cli/commands/studio/views/companion-picker.tsx +0 -95
- package/src/cli/commands/studio/views/companion-selector.tsx +0 -94
- package/src/cli/commands/studio/views/dashboard/changes.tsx +0 -107
- package/src/cli/commands/studio/views/dashboard/index.tsx +0 -19
- package/src/cli/commands/studio/views/document.tsx +0 -842
- package/src/cli/commands/studio/views/error.tsx +0 -20
- package/src/cli/commands/studio/views/reports/index.tsx +0 -49
- package/src/cli/commands/studio/views/selection-fields.tsx +0 -14
- package/src/cli/commands/studio/views/skills/index.tsx +0 -87
- package/src/cli/commands/studio/views/specs/index.tsx +0 -157
- package/src/cli/commands/studio/views/styles.ts +0 -519
- package/src/cli/commands/studio/views/terminal.tsx +0 -484
- package/src/cli/commands/studio/views/vault/state.ts +0 -43
- package/src/cli/commands/studio/views/warnings.tsx +0 -21
- package/src/cli/commands/studio/views/workflow/index.tsx +0 -21
- package/src/cli/commands/studio/views/workflow/steps.ts +0 -337
- package/src/cli/commands/studio/views/workflow/transcript.tsx +0 -190
- package/src/lib/components/theme.ts +0 -2
- package/src/tools/setup/git-utils.ts +0 -30
- package/src/tools/setup/runtime-documents.ts +0 -291
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{t as e}from"./preload-helper-BLdHbfdN.js";var t,n=new Map,r=4;function i(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function a(e){let t=await fetch(e);if(!t.ok)throw Error(`[wterm] Failed to load WASM from ${e}: ${t.status} ${t.statusText}`);if(typeof WebAssembly.compileStreaming==`function`&&t.headers.get(`Content-Type`)?.trim().toLowerCase()===`application/wasm`)try{return await WebAssembly.compileStreaming(t.clone())}catch{}return WebAssembly.compile(await t.arrayBuffer())}function o(o){if(!o)return t??=e(async()=>{let{WASM_BASE64:e}=await import(`./wasm-inline-C2en61B5.js`);return{WASM_BASE64:e}},[]).then(({WASM_BASE64:e})=>WebAssembly.compile(i(e))).catch(e=>{throw t=void 0,e}),t;typeof document<`u`?o=new URL(o,document.baseURI).href:typeof location<`u`&&(o=new URL(o,location.href).href);let s=o,c=n.get(s);if(c)return n.delete(s),n.set(s,c),c;let l=a(s).catch(e=>{throw n.get(s)===l&&n.delete(s),e});return n.set(s,l),n.size>r&&n.delete(n.keys().next().value),l}var s=2147483648,c=256,l=class e{get dv(){return this._dvBuffer!==this.memory.buffer&&(this._dvBuffer=this.memory.buffer,this._dv=new DataView(this.memory.buffer)),this._dv}constructor(e){this.gridPtr=0,this.dirtyPtr=0,this.writeBufferPtr=0,this.cellSize=12,this.gridStride=0,this.encoder=new TextEncoder,this.decoder=new TextDecoder,this._dvBuffer=null,this.clusterCache=new Map,this.linkCache=new Map,this.clearedRowIds=new Uint32Array,this.exports=e.exports,this.memory=this.exports.memory}static async load(t){let n=await o(t),r=await WebAssembly.instantiate(n);return new e(r)}init(e,t){this.exports.init(e,t),this.linkCache.clear(),this.clusterCache.clear(),this._updatePointers()}_updatePointers(){this.gridPtr=this.exports.getGridPtr(),this.dirtyPtr=this.exports.getDirtyPtr(),this.writeBufferPtr=this.exports.getWriteBuffer(),this.cellSize=this.exports.getCellSize(),this.gridStride=this.exports.getGridStride()}writeString(e,t){let n=this.encoder.encode(e);this.writeRaw(n,t)}writeRaw(e,t){let n=0;for(;n<e.length;){let r=Math.min(e.length-n,8192);new Uint8Array(this.memory.buffer,this.writeBufferPtr,8192).set(e.subarray(n,n+r)),this.exports.writeBytes(r),this._updatePointers(),n+=r,t?.()}}getCell(e,t){let n=this.gridPtr+(e*this.gridStride+t)*this.cellSize,r=this.dv,i={char:r.getUint32(n,!0),fg:r.getUint16(n+4,!0),bg:r.getUint16(n+6,!0),flags:r.getUint8(n+8),width:r.getUint8(n+9)};return this._resolveCluster(i),this._resolveRgb(i),Object.assign(i,this._readLink(r.getUint16(n+10,!0))),i}setThemeColors(e){this.exports.setThemeColors?.(e.foreground,e.background)}getScrollbackClearCount(){return this.exports.getScrollbackClearCount?.()??0}getCellLinkIndex(e,t){let n=this.gridPtr+(e*this.gridStride+t)*this.cellSize;return this.dv.getUint16(n+10,!0)}getScrollbackLinkIndex(e,t){let n=this.exports.getScrollbackLine(e);return this.dv.getUint16(n+t*this.cellSize+10,!0)}isDirtyRow(e){if(this.isRowContentDirty(e))return!0;let t=this.getRowId(e);return t===null?this.exports.getRowId!==void 0:t!==this.clearedRowIds[e]}isRowContentDirty(e){return new Uint8Array(this.memory.buffer,this.dirtyPtr,this.getRows())[e]!==0}getRowId(e){if(!Number.isInteger(e)||e<0||e>=this.getRows())return null;let t=this.exports.getRowId?.(e)??0;return t===0?null:t>>>0}clearDirty(){let e=this.exports.getRowId;if(e){let t=this.getRows();this.clearedRowIds.length!==t&&(this.clearedRowIds=new Uint32Array(t));for(let n=0;n<t;n++)this.clearedRowIds[n]=e(n)}this.exports.clearDirty()}getCursor(){let e=this.exports.getCursorShape?.()??0;return{row:this.exports.getCursorRow(),col:this.exports.getCursorCol(),visible:this.exports.getCursorVisible()!==0,shape:e===1?`underline`:e===2?`bar`:`block`,blinking:(this.exports.getCursorBlinking?.()??0)!==0}}getCols(){return this.exports.getCols()}getRows(){return this.exports.getRows()}cursorKeysApp(){return this.exports.getCursorKeysApp()!==0}bracketedPaste(){return this.exports.getBracketedPaste()!==0}usingAltScreen(){return this.exports.getUsingAltScreen()!==0}mouseTracking(){let e=this.exports.getMouseTracking();return e===1e3||e===1002||e===1003?e:0}mouseSgr(){return this.exports.getMouseSgr()!==0}mouseEncoding(){switch(this.exports.getMouseEncoding?.()){case 0:return`x10`;case 1:return`utf8`;case 2:return`sgr`;case 3:return`urxvt`;case 4:return`sgr-pixels`;case void 0:return this.mouseSgr()?`sgr`:`x10`;default:return null}}focusEvents(){return this.exports.getFocusEvents()!==0}synchronizedOutput(){return this.exports.getSynchronizedOutput()!==0}synchronizedOutputGeneration(){return this.exports.getSynchronizedOutputGeneration()}kittyKeyboardFlags(){return this.exports.getKittyKeyboardFlags?.()??0}getTitle(){if(this.exports.getTitleChanged()===0)return null;let e=this.exports.getTitlePtr(),t=this.exports.getTitleLen(),n=new Uint8Array(this.memory.buffer,e,t);return this.decoder.decode(n)}getBellCount(){return this.exports.getBellCount?.()??0}getResponse(){let e=this.exports.getResponseLen();if(e===0)return null;let t=this.exports.getResponsePtr(),n=new Uint8Array(this.memory.buffer,t,e),r=this.decoder.decode(n);return this.exports.clearResponse(),r}getResourceState(){let e=this.exports.getHyperlinkCapacity?.(),t=this.exports.getHyperlinkCount?.(),n=this.exports.getHyperlinkRejectedCount?.();return e===void 0||t===void 0||n===void 0?{}:{hyperlinks:{capacity:e,used:t,rejected:n,saturated:t>=e}}}getScrollbackCount(){return this.exports.getScrollbackCount()}getScrollbackDiscardedCount(){return this.exports.getScrollbackDiscardedCount()}getScrollbackCell(e,t){let n=this.exports.getScrollbackLine(e)+t*this.cellSize,r=this.dv,i={char:r.getUint32(n,!0),fg:r.getUint16(n+4,!0),bg:r.getUint16(n+6,!0),flags:r.getUint8(n+8),width:r.getUint8(n+9)};return this._resolveCluster(i),this._resolveRgb(i),Object.assign(i,this._readLink(r.getUint16(n+10,!0))),i}getScrollbackLineLen(e){return this.exports.getScrollbackLineLen(e)}getUnhandledSequences(){let e=this.exports.getDebugLogCount();if(e===0)return[];let t=this.exports.getDebugLogPtr(),n=this.exports.getDebugLogEntrySize(),r=this.exports.getDebugLogMax(),i=Math.min(e,r),a=new DataView(this.memory.buffer),o=[],s=e>=r?e%r:0;for(let e=0;e<i;e++){let i=t+(s+e)%r*n,c=a.getUint8(i);if(c===0)continue;let l=a.getUint8(i+1),u=a.getUint8(i+2),d=[];for(let e=0;e<Math.min(u,4);e++)d.push(a.getUint16(i+4+e*2,!0));o.push({final:String.fromCharCode(c),private:l?String.fromCharCode(l):``,paramCount:u,params:d})}return o}resize(e,t){this.exports.resizeTerminal(e,t),this._updatePointers()}_resolveCluster(e){if(e.char<s)return;let t=e.char-s,n=this.clusterCache.get(t);if(n===void 0){let e=this.exports.getClusterLen?.(t)??0;n=e===0?``:this.decoder.decode(new Uint8Array(this.memory.buffer,this.exports.getClusterPtr(t),e)),this.clusterCache.set(t,n)}e.char=n.codePointAt(0)??32,n.length>String.fromCodePoint(e.char).length&&(e.chars=n)}_resolveRgb(e){if(e.fg>c){let t=this._readRgb(e.fg);t!==void 0&&(e.fgRgb=t)}if(e.bg>c){let t=this._readRgb(e.bg);t!==void 0&&(e.bgRgb=t)}}_readRgb(e){let t=this.exports.getColorRgb?.(e);if(t!==void 0)return t<0||t>16777215?void 0:t}_readLink(e){if(e===0)return;let t=this.linkCache.get(e);if(t)return t;let n=this.exports.getLinkUriLen(e);if(n===0)return;let r=this.decoder.decode(new Uint8Array(this.memory.buffer,this.exports.getLinkUriPtr(e),n)),i=this.exports.getLinkIdLen(e),a=i===0?void 0:this.decoder.decode(new Uint8Array(this.memory.buffer,this.exports.getLinkIdPtr(e),i)),o={linkUri:r,linkId:a,linkKey:a?`e\0${a}\0${r}`:`b\0${e}`};return this.linkCache.set(e,o),o}};function u(e,t){let n=0;for(let r=0;r<e.length&&n<=t;r++){let t=e.charCodeAt(r);t<128?n++:t<2048?n+=2:t>=55296&&t<=56319&&r+1<e.length&&e.charCodeAt(r+1)>=56320&&e.charCodeAt(r+1)<=57343?(n+=4,r++):n+=3}return n}var d=class{constructor(e={}){if(this._ws=null,this._connectionUrl=null,this._reconnectTimer=null,this._drainTimer=null,this._reconnectDelay=1e3,this._closed=!1,this._buffer=[],this._queuedBytes=0,this._backpressured=!1,this._socketPaused=!1,this.url=e.url??null,this._connectionUrl=this.url,this.reconnect=e.reconnect!==!1,this.maxReconnectDelay=e.maxReconnectDelay??3e4,this.maxBufferedBytes=e.maxBufferedBytes??1048576,this.maxBufferedMessages=e.maxBufferedMessages??1024,this.highWaterMark=e.highWaterMark??Math.min(65536,this.maxBufferedBytes),this.lowWaterMark=e.lowWaterMark??Math.floor(this.highWaterMark/4),!Number.isSafeInteger(this.maxBufferedBytes)||this.maxBufferedBytes<=0||!Number.isSafeInteger(this.maxBufferedMessages)||this.maxBufferedMessages<=0||!Number.isSafeInteger(this.highWaterMark)||this.highWaterMark<=0||this.highWaterMark>this.maxBufferedBytes||!Number.isSafeInteger(this.lowWaterMark)||this.lowWaterMark<0||this.lowWaterMark>=this.highWaterMark)throw RangeError(`Invalid WebSocket buffer limits`);this.onData=e.onData??null,this.onOpen=e.onOpen??null,this.onClose=e.onClose??null,this.onError=e.onError??null,this.onBackpressure=e.onBackpressure??null}connect(e){let t=e??this.url;if(!t)throw Error(`No WebSocket URL provided`);let n=this._ws;if(!this._closed&&t===this._connectionUrl&&n&&(n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN))return;let r=new WebSocket(t),i=this._connectionUrl??this.url,a=i!==null&&t!==i;this._cancelTimers(),this._ws=r,this._closed=!1,this._socketPaused=!1,this.url=t,this._connectionUrl=t,a&&this._clearBuffer(),n&&(this._detach(n),n.close()),r.binaryType=`arraybuffer`,r.onopen=()=>{this._ws!==r||this._closed||(this._reconnectDelay=1e3,this._flushBuffer(),this._ws===r&&!this._closed&&this.onOpen?.())},r.onmessage=e=>{this._ws!==r||this._closed||this.onData?.(e.data instanceof ArrayBuffer?new Uint8Array(e.data):e.data)},r.onclose=()=>{if(this._ws===r){this._ws=null,this._detach(r),this._cancelTimers(),this._socketPaused=!1,this.reconnect&&!this._closed&&this._scheduleReconnect();try{this._updatePressure()}finally{this.onClose?.()}}},r.onerror=e=>{if(!(this._ws!==r||this._closed))try{this.onError?.(e)}finally{this._ws===r&&r.close()}},this._updatePressure()}send(e){if(this._closed)throw Error(`WebSocket transport is closed`);let t=this.maxBufferedBytes-this.bufferedAmount;if((typeof e==`string`?u(e,t):e.byteLength)>t||this._buffer.length>=this.maxBufferedMessages)throw RangeError(`WebSocket send buffer limit exceeded`);let n=typeof e==`string`?new TextEncoder().encode(e):new Uint8Array(e);this._buffer.push(n),this._queuedBytes+=n.byteLength,this._flushBuffer()}close(){this._closed=!0,this._cancelTimers(),this._clearBuffer(),this._socketPaused=!1;try{this._ws?.close()}finally{this._updatePressure()}}get connected(){return!this._closed&&this._ws?.readyState===WebSocket.OPEN}get bufferedAmount(){return this._queuedBytes+(this.connected?this._ws.bufferedAmount:0)}get queuedBytes(){return this._queuedBytes}get queuedMessages(){return this._buffer.length}get backpressured(){return this._backpressured}_flushBuffer(){let e=this._ws;if(e&&this.connected){this._socketPaused&&e.bufferedAmount<=this.lowWaterMark&&(this._socketPaused=!1);for(let t=0;!this._socketPaused&&this._buffer.length&&t<64;t++){let t=this._buffer[0];if(e.bufferedAmount>0&&e.bufferedAmount+t.byteLength>this.highWaterMark){this._socketPaused=!0;break}e.send(t),this._buffer.shift(),this._queuedBytes-=t.byteLength,e.bufferedAmount>=this.highWaterMark&&(this._socketPaused=!0)}(this._buffer.length||e.bufferedAmount)&&this._drainTimer===null&&(this._drainTimer=setTimeout(()=>{this._drainTimer=null,this._flushBuffer()},16))}this._updatePressure()}_updatePressure(){let e=this.bufferedAmount,t=this._buffer.length>=this.maxBufferedMessages,n=this._backpressured?e>this.lowWaterMark||t:e>=this.highWaterMark||t;n!==this._backpressured&&(this._backpressured=n,this.onBackpressure?.(n))}_clearBuffer(){this._buffer=[],this._queuedBytes=0}_cancelTimers(){this._reconnectTimer!==null&&clearTimeout(this._reconnectTimer),this._drainTimer!==null&&clearTimeout(this._drainTimer),this._reconnectTimer=this._drainTimer=null}_detach(e){e.onopen=e.onmessage=e.onclose=e.onerror=null}_scheduleReconnect(){this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=null,!this._closed&&this.reconnect&&this.connect()},this._reconnectDelay),this._reconnectDelay=Math.min(this._reconnectDelay*2,this.maxReconnectDelay)}},f=33554432,p=32768;function m(e){return e!==void 0&&Number.isFinite(e)&&e>0}function h(e){return Number.isSafeInteger(e)&&e>=0}function g(...e){let t=1;for(let n of e)if(!h(n)||(t*=n,!Number.isSafeInteger(t)))return null;return t}function _(e){return`${e.placementKey}:${e.imageId}:${e.imageVersion}`}var v=class{constructor(e,t={}){this.layer=null,this.flowSpacer=null,this.canvases=new Map,this.canvasAllocations=new Map,this.canvasBytes=0,this.cache=new Map,this.generation=-1,this.flowRows=new Map,this.container=e,this.maxImageWidth=m(t.maxImageWidth)?t.maxImageWidth:void 0,this.maxImageHeight=m(t.maxImageHeight)?t.maxImageHeight:void 0}setup(){this.destroy();let e=document.createElement(`div`);e.className=`term-image-flow-spacer`,e.setAttribute(`aria-hidden`,`true`),this.container.appendChild(e),this.flowSpacer=e;let t=document.createElement(`div`);t.className=`term-images`,t.setAttribute(`aria-hidden`,`true`),t.setAttribute(`role`,`presentation`),this.container.appendChild(t),this.layer=t,this.generation=-1}reconcile(e,t){let n=e.getGraphicsState,r=e.getGraphicsImage;if(!n||!r||!this.layer){this.clearCanvases(),this.clearFlowReservations();return}let i;try{i=n.call(e)}catch{this.clearCanvases(),this.clearFlowReservations();return}if(!i||!Number.isSafeInteger(i.generation)||!Array.isArray(i.images)||!Array.isArray(i.placements)){this.clearCanvases(),this.clearFlowReservations();return}let a=new Map;for(let e of i.images)Number.isSafeInteger(e.imageId)&&e.imageId>0&&Number.isSafeInteger(e.version)&&e.version>0&&Number.isSafeInteger(e.width)&&Number.isSafeInteger(e.height)&&e.width>0&&e.height>0&&a.set(`${e.imageId}:${e.version}`,e);let o=this.visiblePixelArea(e,t),s=o?this.reconcileFlowReservations(e,i,t,a,o):new Map;o||this.clearFlowReservations();let c=o?this.visiblePlacements(e,i,t,a,o,s):[],l=new Set,u=new Map;for(let e of c){let t=_(e),n=`${e.imageId}:${e.imageVersion}`;a.has(n)&&(l.add(t),u.set(n,(u.get(n)??0)+1))}let d=i.generation!==this.generation;this.generation=i.generation;for(let[e,t]of this.canvases)l.has(e)||this.removeCanvas(e);for(let[e,t]of this.cache)u.has(e)?t.refs=u.get(e):this.cache.delete(e);for(let n of c){let i=_(n),c=`${n.imageId}:${n.imageVersion}`;if(!l.has(i))continue;let f=a.get(c);if(!f)continue;let p=this.cache.get(c);if(!p){let t;try{t=r.call(e,n.imageId,n.imageVersion)}catch{t=null}if(!t||!this.validImage(t,f.width,f.height))continue;p={data:t,refs:u.get(c)??0},this.cache.set(c,p)}let m=this.canvases.get(i),h=m??this.createCanvas(i);if(h){if(d||!m){let e=!1;try{e=this.paint(h,i,p.data,n,t,o,s.get(n.row)??0)}catch{e=!1}e||this.removeCanvas(i)}else this.position(h,n,t,s.get(n.row)??0)}}}destroy(){this.clearCanvases(),this.layer?.remove(),this.flowSpacer?.remove(),this.layer=null,this.flowSpacer=null,this.cache.clear(),this.generation=-1,this.clearFlowReservations()}createCanvas(e){if(!this.layer)return null;let t=document.createElement(`canvas`);return t.className=`term-image`,t.setAttribute(`aria-hidden`,`true`),t.tabIndex=-1,t.draggable=!1,this.layer.appendChild(t),this.canvases.set(e,t),t}clearCanvases(){for(let e of this.canvases.keys())this.removeCanvas(e);this.canvasAllocations.clear(),this.canvasBytes=0,this.cache.clear()}removeCanvas(e){this.canvases.get(e)?.remove(),this.canvases.delete(e);let t=this.canvasAllocations.get(e)??0;this.canvasAllocations.delete(e),this.canvasBytes=Math.max(0,this.canvasBytes-t)}reconcileFlowReservations(e,t,n,r,i){let a,o;try{o=e.getRows(),a=n.scrollbackCount+o}catch{return this.flowRows.size>0&&this.clearFlowReservations(),new Map}if(!Number.isSafeInteger(o)||o<0||!Number.isSafeInteger(a)||a<0)return this.flowRows.size>0&&this.clearFlowReservations(),new Map;let s=new Map;for(let e of t.placements){if(!this.validPlacement(e,a)||e.rows!==0||e.row<n.scrollbackCount)continue;let t=r.get(`${e.imageId}:${e.imageVersion}`);if(!t)continue;let o=this.destinationSize(e,e.sourceWidth||t.width,e.sourceHeight||t.height,n,i);if(!o)continue;let c=e.offsetY+o.height;m(c)&&s.set(e.row,Math.max(s.get(e.row)??0,c))}if(s.size===0)return this.flowRows.size>0&&this.clearFlowReservations(),new Map;this.clearFlowReservations();let c=this.container.querySelectorAll(`.term-row:not(.term-scrollback-row)`);for(let e of c)e.style.transform=``;let l=new Map,u=0,d=n.scrollbackCount;for(let e=0;e<o;e++){let t=d+e;u>0&&l.set(t,u);let n=s.get(t)??0,r=c[e],i=u+n;r&&i>0&&(r.style.transform=`translateY(${i}px)`),u+=n}return this.flowSpacer&&(this.flowSpacer.style.height=`${u}px`),this.container.parentElement?.classList.toggle(`has-image-flow`,u>0),this.flowRows=s,l}clearFlowReservations(){if(this.flowRows.size===0){this.flowSpacer?.style.setProperty(`height`,`0px`),this.container.parentElement?.classList.remove(`has-image-flow`);return}let e=this.container.querySelectorAll(`.term-row:not(.term-scrollback-row)`);for(let t of e)t.style.transform=``;this.flowSpacer&&(this.flowSpacer.style.height=`0px`),this.container.parentElement?.classList.remove(`has-image-flow`),this.flowRows.clear()}validImage(e,t,n){let r=g(e.width,e.height,4);return Number.isSafeInteger(e.width)&&Number.isSafeInteger(e.height)&&e.width>0&&e.height>0&&e.width===t&&e.height===n&&e.rgba instanceof Uint8Array&&r!==null&&e.rgba.byteLength===r}visiblePlacements(e,t,n,r,i,a){if(!m(n.rowHeight)||!m(n.charWidth)||!Number.isFinite(n.scrollTop))return[];let o;try{o=n.scrollbackCount+e.getRows()}catch{return[]}if(!Number.isSafeInteger(o)||o<0)return[];let s=n.scrollTop-n.overscanRows*n.rowHeight,c=n.scrollTop+Math.max(n.clientHeight,n.rowHeight)+n.overscanRows*n.rowHeight;return t.placements.filter(e=>{if(!this.validPlacement(e,o))return!1;let t=r.get(`${e.imageId}:${e.imageVersion}`);if(!t)return!1;let l=this.destinationSize(e,e.sourceWidth||t.width,e.sourceHeight||t.height,n,i);if(!l)return!1;let u=e.row*n.rowHeight+e.offsetY+(a.get(e.row)??0),d=u+l.height;return Number.isFinite(u)&&Number.isFinite(d)&&u<c&&d>s})}validPlacement(e,t){return typeof e.placementKey==`string`&&e.placementKey.length>0&&h(e.imageId)&&e.imageId>0&&h(e.imageVersion)&&e.imageVersion>0&&h(e.row)&&e.row<t&&h(e.col)&&h(e.offsetX)&&h(e.offsetY)&&h(e.sourceX)&&h(e.sourceY)&&h(e.sourceWidth)&&h(e.sourceHeight)&&h(e.columns)&&h(e.rows)&&Number.isSafeInteger(e.z)&&Number.isSafeInteger(e.row+(e.rows||1))}position(e,t,n,r=0){let i=t.rows===0?t.offsetX:t.col*n.charWidth+t.offsetX,a=t.row*n.rowHeight+t.offsetY+r;Number.isFinite(i)&&(e.style.left=`${i}px`),Number.isFinite(a)&&(e.style.top=`${a}px`)}paint(e,t,n,r,i,a,o=0){if(!this.validPlacement(r,2**53-1))return!1;let s=r.sourceX,c=r.sourceY,l=r.sourceWidth||n.width,u=r.sourceHeight||n.height;if(!Number.isSafeInteger(s)||!Number.isSafeInteger(c)||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||s<0||c<0||l<=0||u<=0||s+l>n.width||c+u>n.height)return!1;let d=this.destinationSize(r,l,u,i,a);if(!d)return!1;let{width:f,height:m}=d,h=Math.max(1,Math.ceil(f)),_=Math.max(1,Math.ceil(m));if(!Number.isSafeInteger(h)||!Number.isSafeInteger(_)||h>p||_>p)return!1;let v=g(h,_,4);if(v===null||!this.resizeCanvas(e,t,h,_,v))return!1;this.position(e,r,i,o),e.style.width=`${f}px`,e.style.height=`${m}px`,e.style.zIndex=String(r.z),e.style.pointerEvents=`none`;let y=e.getContext(`2d`);if(!y)return!1;let b=document.createElement(`canvas`);b.width=n.width,b.height=n.height;let x=b.getContext(`2d`);if(!x)return!1;let S=new Uint8ClampedArray(n.rgba),C=typeof ImageData<`u`?new ImageData(S,n.width,n.height):x.createImageData?.(n.width,n.height)??{data:S,width:n.width,height:n.height};return`data`in C&&C.data!==S&&C.data.set(S),x.putImageData(C,0,0),y.clearRect(0,0,h,_),y.drawImage(b,s,c,l,u,0,0,h,_),!0}destinationSize(e,t,n,r,i){if(!h(t)||!h(n)||t<=0||n<=0)return null;let a=e.columns*r.charWidth,o=e.rows*r.rowHeight,s=m(a)&&e.columns>0?a:m(o)&&e.rows>0?t/n*o:t,c=m(o)&&e.rows>0?o:m(a)&&e.columns>0?n/t*a:n;if(!m(s)||!m(c)||!Number.isFinite(e.offsetY+c)||!i)return null;let l=Math.min(1,i.width/s,i.height/c,this.maxImageWidth===void 0?1:this.maxImageWidth/s,this.maxImageHeight===void 0?1:this.maxImageHeight/c);return m(l)?{width:s*l,height:c*l}:null}visiblePixelArea(e,t){let n,r;try{n=e.getCols(),r=e.getRows()}catch{return null}if(!h(n)||!h(r)||n<=0||r<=0||!m(t.charWidth)||!m(t.rowHeight))return null;let i=n*t.charWidth,a=r*t.rowHeight;return!m(i)||!m(a)||!Number.isSafeInteger(Math.ceil(i))||!Number.isSafeInteger(Math.ceil(a))?null:{width:Math.min(i,p),height:Math.min(a,p)}}resizeCanvas(e,t,n,r,i){let a=this.canvasAllocations.get(t)??0;if(i>f-this.canvasBytes+a)return!1;try{e.width=n,e.height=r}catch{return!1}return this.canvasBytes=this.canvasBytes-a+i,this.canvasAllocations.set(t,i),!0}},y=new WeakMap;function b(e){let t=y.get(e);if(!t){t={knownEmpty:!1},y.set(e,t);let n=()=>x(e);e.addEventListener(`selectionchange`,n);for(let t of[`pointerdown`,`mousedown`,`touchstart`,`keydown`])e.addEventListener(t,n,!0)}if(t.knownEmpty)return!1;let n=e.getSelection();return t.knownEmpty=!n||n.rangeCount===0||n.isCollapsed,!t.knownEmpty}function x(e){let t=y.get(e);t&&(t.knownEmpty=!1)}function S(e,t,n){let r=[],i=t;for(let a of e.specialCells)if(!(a.end<=t)){if(a.start>=n)break;i<a.start&&r.push(e.text.slice(i,a.start)),a.omit||r.push(e.text.slice(a.start,a.end)),i=a.end}return i<n&&r.push(e.text.slice(i,n)),r.join(``)}function C(e,t){return x(e.ownerDocument),w(e,t)?.text??null}function w(e,t){if(!b(e.ownerDocument))return null;let n=e.ownerDocument.getSelection();if(!n||n.isCollapsed||n.rangeCount!==1)return null;let r=n.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let i=e.ownerDocument.activeElement;if(i&&(i.tagName===`INPUT`||i.tagName===`TEXTAREA`)){let e=i;if(e.selectionStart!==e.selectionEnd)return null}let a=[],o,s,c;for(let n of t){let{element:t,content:i}=n;if(!r.intersectsNode(t))continue;let l=e.ownerDocument.createRange();l.selectNodeContents(t),t.contains(r.startContainer)&&l.setStart(r.startContainer,r.startOffset),t.contains(r.endContainer)&&l.setEnd(r.endContainer,r.endOffset);let u=e.ownerDocument.createRange();u.selectNodeContents(t),u.setEnd(l.startContainer,l.startOffset);let d=u.toString().length,f=d+l.toString().length;if(t.textContent!==i.text)return null;if(o??={row:n,offset:d},s={row:n,offset:f===i.text.length&&!i.metadata?.wrapsToNext?Math.max(d,i.text.replace(/ +$/,``).length):f},c){if(n.row!==c.row+1)return null;c.content.metadata?.wrapsToNext&&i.metadata?.continuesPrevious||a.push(`
|
|
2
|
+
`)}let p=d===f?``:S(i,d,f);f===i.text.length&&!i.metadata?.wrapsToNext&&(p=p.replace(/ +$/,``)),a.push(p),c=n}return o&&s?{text:a.join(``),first:o,last:s,backward:n.anchorNode!==r.startContainer||n.anchorOffset!==r.startOffset}:null}function T(e,t,n){let r=0;for(let i of e.specialCells){if(t>=i.start&&t<i.end&&!n||t>i.start&&t<=i.end&&n)return{col:i.col,after:n};i.end<=t&&(r+=i.width-(i.end-i.start))}let i=t>0&&(n||t===e.text.length);return{col:t+r-+!!i,after:i}}function E(e,t,n){let r=0;for(let i of e.specialCells){if(t>=i.col&&t<i.col+i.width)return n?i.end:i.start;i.col<t&&(r+=i.end-i.start-i.width)}return t+r+ +!!n}function D(e,t){let n=e.ownerDocument.createTreeWalker(e,4),r;for(;r=n.nextNode();){let e=r.textContent?.length??0;if(t<=e)return[r,t];t-=e}return null}var O=1e3,ee=1048576,te=new Set(` '"│\`|:;,()[]{}<>$`);function ne(e,t,n){let r=e.getScrollbackCount(),i=r+e.getRows(),a=e.getCols(),o={char:0,fg:256,bg:256,flags:0};if(!Number.isInteger(t.row)||!Number.isInteger(t.col)||t.row<0||t.row>=i||t.col<0||t.col>=a)return null;let s=t=>t.row<r?t.col<e.getScrollbackLineLen(r-t.row-1)?e.getScrollbackCell(r-t.row-1,t.col):o:e.getCell(t.row-r,t.col),c=t=>t<r?e.getScrollbackLineLen(r-t-1)<=a?e.getScrollbackRowMetadata?.(r-t-1):null:e.getRowMetadata?.(t-r),l=e=>e>=0&&e+1<i&&c(e)?.wrapsToNext&&c(e+1)?.continuesPrevious,u=(e,t)=>{let n=e.col+t;if(n>=0&&n<a)return{row:e.row,col:n};let r=e.row+t;return l(Math.min(r,e.row))?{row:r,col:t===1?0:a-1}:null},d={...t};if(s(d).spacerHead)return null;s(d).width===0&&d.col>0&&d.col--;let f=e=>{let t=s(e);return t.chars??String.fromCodePoint(t.char||32)},p=e=>te.has(String.fromCodePoint(e.codePointAt(0)??32)),m=p(f(d)),h=f(d).length,g=1,_=h>ee,v=d,y=d,b=e=>{let t=d,r=d;for(;;){let i=u(t,e);if(!i)return r;if(++g>2097152)return _=!0,r;let a=s(i);if(a.width!==0&&!a.spacerHead){let e=a.chars??String.fromCodePoint(a.char||32);if(n===`word`&&p(e)!==m)return r;h+=e.length,r=i}let o=e===-1?i.row:v.row;if((e===1?i.row:d.row)-o>=1e3||h>1048576)return _=!0,r;t=i}};return v=b(-1),_||(y=b(1)),_?null:{start:v,end:y}}var re=65536;function ie(e,t,n){let r=e.getScrollbackCount(),i=r+e.getRows(),a=e.getCols();for(let e of[t,n])if(!Number.isInteger(e.row)||!Number.isInteger(e.col)||e.row<0||e.row>=i||e.col<0||e.col>=a)return null;let o=Math.min(t.row,n.row),s=Math.max(t.row,n.row),c=Math.min(t.col,n.col),l=Math.max(t.col,n.col),u=s-o+1;if(u>1e3||u*(l-c+2)>re)return null;let d=[],f=[],p=u-1;for(let t=o;t<=s;t++){let n=r-t-1,i=t<r?e.getScrollbackLineLen(n):a,o=a=>a>=i?null:t<r?e.getScrollbackCell(n,a):e.getCell(t-r,a),s=c;s>0&&o(s)?.width===0&&o(s-1)?.width===2&&s--;let u=l+1,m=``;for(let e=s;e<=l;e++){let t=o(e);if(t?.width===0||t?.spacerHead)continue;let n=t?.chars??String.fromCodePoint(t?.char||32);if(p+=n.length,p>1048576)return null;m+=n,u=Math.max(u,Math.min(a,e+(t?.width??1)))}d.push({row:t,left:s,right:u}),f.push(m)}return{rows:d,text:f.join(`
|
|
3
|
+
`)}}var k=O,ae=class{constructor(e){this.terminal=e,this.current=null,this.painted=!0}matches(){if(!b(this.terminal.ownerDocument))return!1;let e=this.terminal.ownerDocument.getSelection(),t=this.current?.native;return!!e&&!!t&&e.anchorNode===t.anchorNode&&e.anchorOffset===t.anchorOffset&&e.focusNode===t.focusNode&&e.focusOffset===t.focusOffset}capture(e,t){if(!b(this.terminal.ownerDocument)){this.dispose();return}let n=this.terminal.ownerDocument.activeElement;if(n&&(n.tagName===`INPUT`||n.tagName===`TEXTAREA`)){let e=n;if(e.selectionStart!==e.selectionEnd){this.dispose();return}}if(this.current&&this.matches()||(this.dispose(),!this.painted||!e.trackPosition))return;let r=w(this.terminal,t);if(!r||!r.text.length||r.last.row.row-r.first.row.row>=k||r.text.length>1048576)return;let i=T(r.first.row.content,r.first.offset,!1),a=T(r.last.row.content,r.last.offset,!0),o=e.trackPosition({row:r.first.row.row,col:i.col});if(!o)return;let s=e.trackPosition({row:r.last.row.row,col:a.col});if(!s){o.dispose();return}let c=this.terminal.ownerDocument.getSelection();this.current={start:{pin:o,after:i.after},end:{pin:s,after:a.after},text:r.text,backward:r.backward,native:this.snapshot(c)}}beforeMutation(e,t){this.capture(e,t),this.painted=!1}beforeRender(e,t){this.capture(e,t);let n=this.current?.start.pin.resolve(),r=this.current?.end.pin.resolve();return!n||!r||r.row<n.row||r.row===n.row&&r.col<n.col||r.row-n.row>=k?(this.clear(),null):{start:n,end:r}}afterRender(e,t){this.painted=!0;let n=this.current;if(!n||!t)return;let r=Array.from(e),i=(e,t)=>{let n=r.find(t=>t.row===e.row);return n&&D(n.element,E(n.content,e.col,t))},a=i(t.start,n.start.after),o=i(t.end,n.end.after),s=this.terminal.ownerDocument.getSelection();if(!a||!o||!s){this.clear();return}let c=n.backward?o:a,l=n.backward?a:o;(s.anchorNode!==c[0]||s.anchorOffset!==c[1]||s.focusNode!==l[0]||s.focusOffset!==l[1])&&(x(this.terminal.ownerDocument),s.setBaseAndExtent(...c,...l)),n.native=this.snapshot(s),w(this.terminal,r)?.text!==n.text&&this.clear()}snapshot(e){return{anchorNode:e.anchorNode,anchorOffset:e.anchorOffset,focusNode:e.focusNode,focusOffset:e.focusOffset}}clear(){this.current&&this.matches()&&(x(this.terminal.ownerDocument),this.terminal.ownerDocument.getSelection()?.removeAllRanges()),this.dispose()}dispose(){this.current?.start.pin.dispose(),this.current?.end.pin.dispose(),this.current=null}},oe=256,se=`var(--term-app-fg, var(--term-fg))`,A=`var(--term-app-bg, var(--term-bg))`,ce=1,le=2,ue=4,de=8,j=32,fe=64,pe=128,me=10;function M(e){return`rgb(${e>>16&255},${e>>8&255},${e&255})`}function he(e){return e===oe?null:e<16?`var(--term-color-${e})`:M(ge(e))}function ge(e){if(e<232){let t=e-16;return Math.floor(t/36)*51<<16|Math.floor(t/6)%6*51<<8|t%6*51}let t=(e-232)*10+8;return t<<16|t<<8|t}var _e=new Uint8Array(new Uint32Array([1]).buffer)[0]===1;function N(e,t){if(t===void 0){if(e<16||e>255)return;t=ge(e)}return _e?(4278190080|(t&255)<<16|t&65280|t>>>16&255)>>>0:(t<<8|255)>>>0}function P(e,t){return t===void 0?he(e):M(t)}function F(e,t){return t===void 0?he(e):M(t)}function ve(e){return e.flags&j?N(e.fg,e.fgRgb):N(e.bg,e.bgRgb)}function I({fg:e,bg:t,flags:n,fgRgb:r,bgRgb:i,underlineStyle:a,underlineRgb:o},s=!0){let c=n&j,l=c?F(t,i)??A:P(e,r),u=s?c?P(e,r)??se:F(t,i):null,d=``;l&&(d+=`color:${l};`),u&&(d+=`background:${u};`),n&ce&&(d+=`font-weight:bold;`),n&le&&(d+=`opacity:0.5;`),n&ue&&(d+=`font-style:italic;`);let f=[],p=a??(n&de?`single`:`none`);return p!==`none`&&f.push(`underline`),n&pe&&f.push(`line-through`),f.length&&(d+=`text-decoration:${f.join(` `)};`),p!==`none`&&(d+=`text-decoration-style:${p===`curly`?`wavy`:p===`double`||p===`dotted`||p===`dashed`?p:`solid`};text-decoration-skip-ink:none;`,o!==void 0&&(d+=`text-decoration-color:${M(o)};`)),n&fe&&(d+=`visibility:hidden;`),d}function L(e){return e.replace(/(^|;)color:/g,`$1--term-cell-fg:`).replace(/(^|;)background:/g,`$1--term-cell-bg:`)}function R(e){return e===1?``:`--term-span-cols:${e};`}function ye(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}function be(e,t,n){let r=ye(n),i=!t.includes(`text-decoration:underline line-through;`);i||(t=t.replace(`text-decoration:underline line-through;`,`text-decoration:underline;`),r=`<span style="text-decoration:line-through solid currentColor;">${r}</span>`);let a=`<span${e?` class="${e}"`:``}${t?` style="${t}"`:``}>`;return{html:`${a}${r}</span>`,opening:i?a:void 0,text:i?n:void 0}}function xe(e){if(e)try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t.href:void 0}catch{return}}function Se(e){return e.linkUri?e.linkKey??`fallback\0${e.linkId??``}\0${e.linkUri}`:``}function Ce(e,t,n,r,i){let a=P(e,r)||se,o=F(t,i)||A;return n&j?{fg:o,bg:a}:{fg:a,bg:o}}var z=`round(calc(var(--term-row-height) * 0.125), 1px)`,we=`round(calc(var(--term-row-height) * 0.25), 1px)`,Te=`round(calc(var(--term-row-height) * 0.375), 1px)`,B=`round(calc(var(--term-row-height) * 0.5), 1px)`,Ee=`round(calc(var(--term-row-height) * 0.625), 1px)`,De=`round(calc(var(--term-row-height) * 0.75), 1px)`,Oe=`round(calc(var(--term-row-height) * 0.875), 1px)`;function ke(e,t,n){switch(e){case 9600:return`linear-gradient(${t} ${B},${n} ${B})`;case 9601:return`linear-gradient(${n} ${Oe},${t} ${Oe})`;case 9602:return`linear-gradient(${n} ${De},${t} ${De})`;case 9603:return`linear-gradient(${n} ${Ee},${t} ${Ee})`;case 9604:return`linear-gradient(${n} ${B},${t} ${B})`;case 9605:return`linear-gradient(${n} ${Te},${t} ${Te})`;case 9606:return`linear-gradient(${n} ${we},${t} ${we})`;case 9607:return`linear-gradient(${n} ${z},${t} ${z})`;case 9608:return t;case 9609:return`linear-gradient(to right,${t} 87.5%,${n} 87.5%)`;case 9610:return`linear-gradient(to right,${t} 75%,${n} 75%)`;case 9611:return`linear-gradient(to right,${t} 62.5%,${n} 62.5%)`;case 9612:return`linear-gradient(to right,${t} 50%,${n} 50%)`;case 9613:return`linear-gradient(to right,${t} 37.5%,${n} 37.5%)`;case 9614:return`linear-gradient(to right,${t} 25%,${n} 25%)`;case 9615:return`linear-gradient(to right,${t} 12.5%,${n} 12.5%)`;case 9616:return`linear-gradient(to right,${n} 50%,${t} 50%)`;case 9617:return`color-mix(in srgb,${t} 25%,${n})`;case 9618:return`color-mix(in srgb,${t} 50%,${n})`;case 9619:return`color-mix(in srgb,${t} 75%,${n})`;case 9620:return`linear-gradient(${t} ${z},${n} ${z})`;case 9621:return`linear-gradient(to right,${n} 87.5%,${t} 87.5%)`;default:{let r={9622:[!1,!1,!0,!1],9623:[!1,!1,!1,!0],9624:[!0,!1,!1,!1],9625:[!0,!1,!0,!0],9626:[!0,!1,!1,!0],9627:[!0,!0,!0,!1],9628:[!0,!0,!1,!0],9629:[!1,!0,!1,!1],9630:[!1,!0,!0,!1],9631:[!1,!0,!0,!0]}[e];if(!r)return t;let[i,a,o,s]=r;if(i&&a&&o&&s)return t;let c=[],l=[`0 0`,`100% 0`,`0 100%`,`100% 100%`];return r.forEach((e,n)=>{e&&c.push(`linear-gradient(${t},${t}) ${l[n]}/50% 50% no-repeat`)}),c.push(n),c.join(`,`)}}}var Ae={9472:`lr`,9474:`ud`,9484:`dr`,9488:`dl`,9492:`ur`,9496:`ul`,9500:`udr`,9508:`udl`,9516:`dlr`,9524:`ulr`,9532:`udlr`,9588:`l`,9589:`u`,9590:`r`,9591:`d`},je={9473:`lr`,9475:`ud`,9487:`dr`,9491:`dl`,9495:`ur`,9499:`ul`,9507:`udr`,9515:`udl`,9523:`dlr`,9531:`ulr`,9547:`udlr`,9592:`l`,9593:`u`,9594:`r`,9595:`d`},Me={9581:`tl`,9582:`tr`,9583:`br`,9584:`bl`},V={};function Ne(e,t){let n=`var(--term-box-stroke)`,r=`calc(50% + ${n})`,i=`calc(50% + ${n})`;for(let[a,o]of Object.entries(e)){let e=[];o.includes(`u`)&&o.includes(`d`)?e.push([`center center`,`${n} 100%`]):(o.includes(`u`)&&e.push([`center top`,`${n} ${r}`]),o.includes(`d`)&&e.push([`center bottom`,`${n} ${r}`])),o.includes(`l`)&&o.includes(`r`)?e.push([`center center`,`100% ${n}`]):(o.includes(`l`)&&e.push([`left center`,`${i} ${n}`]),o.includes(`r`)&&e.push([`right center`,`${i} ${n}`])),V[Number(a)]={className:t,style:`background-image:${e.map(()=>`linear-gradient(currentColor,currentColor)`).join(`,`)};background-position:${e.map(([e])=>e).join(`,`)};background-size:${e.map(([,e])=>e).join(`,`)};background-repeat:no-repeat;`}}}Ne(Ae,`term-box`),Ne(je,`term-box term-box-heavy`);for(let[e,t]of Object.entries(Me))V[Number(e)]={className:`term-box term-box-round term-box-round-${t}`,style:``};var Pe=class{get hasImageFlow(){return this.container.parentElement?.classList.contains(`has-image-flow`)??!1}constructor(e,t={}){this.rows=0,this.cols=0,this.rowEls=[],this.prevCursorRow=-1,this.prevCursorCol=-1,this.prevCursorVisible=!1,this.rowIds=[],this._scrollbackRowEls=[],this._scrollbackKeys=[],this._scrollbackRowHeight=0,this._scrollbackGapSpacers=[],this._renderedScrollbackCount=-1,this._renderedDiscardedCount=-1,this._scrollbackTopSpacer=null,this._scrollbackBottomSpacer=null,this.rowText=new WeakMap,this.rowParts=new WeakMap,this.rowBackground=new WeakMap,this.selection=null,this.needsSetup=!1,this.colorsChanged=!1,this.painted=!1,this.cellContext=null,this.cellImage=null,this.cellPixels=null,this.cellEdges=null,this.cellTop=null,this.cellBottom=null,this.cellBandUsed=[],this.cellEnabled=!1,this.cellSuspended=!1,this.cellRowHeight=0,this.cellCharWidth=0,this.container=e,this.colorHost=t.colorHost??e,this.graphics=new v(e,t),this.searchLayer=document.createElement(`div`),this.searchLayer.className=`term-search-layer`,this.searchLayer.setAttribute(`aria-hidden`,`true`),this.cellCanvas=document.createElement(`canvas`),this.cellCanvas.className=`term-cell-canvas`,this.cellCanvas.setAttribute(`aria-hidden`,`true`),this.cellCanvas.addEventListener(`contextrestored`,()=>{this.cellImage&&this.cellContext?.putImageData(this.cellImage,0,0)})}setup(e,t){this.cols=e,this.rows=t,this.container.innerHTML=``,this.rowText=new WeakMap,this.rowParts=new WeakMap,this.rowBackground=new WeakMap,this.rowEls=[],this.rowIds=[],this._scrollbackRowEls=[],this._scrollbackKeys=[],this._scrollbackGapSpacers=[],this._renderedScrollbackCount=-1,this._renderedDiscardedCount=-1,this.cellEnabled=!1,this.cellRowHeight=0,this.cellCharWidth=0,this.releaseCellImage();let n=document.createDocumentFragment();this._scrollbackTopSpacer=document.createElement(`div`),this._scrollbackTopSpacer.className=`term-scrollback-spacer`,n.appendChild(this._scrollbackTopSpacer),this._scrollbackBottomSpacer=document.createElement(`div`),this._scrollbackBottomSpacer.className=`term-scrollback-spacer`,n.appendChild(this._scrollbackBottomSpacer);for(let e=0;e<t;e++){let e=document.createElement(`div`);e.className=`term-row`,this.rowBackground.set(e,``),n.appendChild(e),this.rowEls.push(e)}this.container.appendChild(n),this.container.appendChild(this.cellCanvas),this.searchLayer.replaceChildren(),this.container.appendChild(this.searchLayer),this.graphics.setup(),this.prevCursorRow=-1,this.prevCursorCol=-1}syncCellCanvas(e){let t=e?.rowHeight??0,n=e?.charWidth??0;if(!(Number.isInteger(t)&&t>0&&Number.isFinite(n)&&n>0&&!this.hasImageFlow&&!this.cellSuspended&&(this.cellContext??=this.cellCanvas.getContext(`2d`))!==null)){let e=this.cellEnabled;return this.cellEnabled=!1,e&&this.releaseCellImage(),e}if(this.cellEnabled&&this.cellRowHeight===t&&this.cellCharWidth===n)return!1;let r=new Int32Array(this.cols+1);for(let e=0;e<=this.cols;e++)r[e]=Math.round(e*n);return this.releaseCellImage(),this.cellEnabled=!0,this.cellRowHeight=t,this.cellCharWidth=n,this.cellEdges=r,this.cellTop=new Uint32Array(this.cols),this.cellBottom=new Uint32Array(this.cols),!0}releaseCellImage(){this.cellImage=null,this.cellPixels=null,this.cellBandUsed=[],this.cellCanvas.width=0,this.cellCanvas.height=0,this.cellCanvas.hidden=!0}ensureCellImage(){if(this.cellImage)return!0;if(!this.cellContext)return!1;let e=Math.max(1,this.cellEdges[this.cols]),t=this.rows*this.cellRowHeight;return this.cellCanvas.width=e,this.cellCanvas.height=t,this.cellCanvas.style.width=`${e}px`,this.cellCanvas.style.height=`${t}px`,this.cellCanvas.hidden=!1,this.cellImage=this.cellContext.createImageData(e,t),this.cellPixels=new Uint32Array(this.cellImage.data.buffer),!0}paintCellBand(e,t){if(!t&&!this.cellBandUsed[e]||!this.ensureCellImage())return;let n=this.cellPixels,r=this.cellImage,i=r.width,a=this.cellRowHeight,o=e*a*i;if(!t)n.fill(0,o,o+a*i);else{let e=this.cellEdges,t=this.cellTop,r=this.cellBottom,s=Math.round(a/2),c=o+s*i;for(let i=0;i<this.cols;i++)n.fill(t[i],o+e[i],o+e[i+1]),n.fill(r[i],c+e[i],c+e[i+1]);for(let e=1;e<a;e++){if(e===s)continue;let t=e<s?o:c;n.copyWithin(o+e*i,t,t+i)}}this.cellBandUsed[e]=t,this.cellContext.putImageData(r,0,0,0,e*a,i,a)}_buildRowContent(e,t,n,r,i){let a=[],o=``,s={text:``,specialCells:[],metadata:null},c=(e,t,n=1,r=!1)=>{let i=s.text.length;s.text+=e,(e.length!==n||n>1||r)&&s.specialCells.push({start:i,end:s.text.length,col:t,width:n,omit:r})},l=``,u=``,d=[],f=0,p=``,m,h=``,g,_=n>=this.cols,v=i>=0&&this.cellEnabled?this.cellTop:null,y=this.cellBottom;v&&(v.fill(0),y.fill(0));let b=!1,x=``,S=0,C=(e,t,n)=>{let r=xe(n),i=r?t:``;i!==h&&(h&&a.push({html:o+`</a>`}),i&&(o=`<a class="term-link" href="${ye(r)}" target="_blank" rel="noopener noreferrer">`),h=i),h?o+=e.html:a.push(e)},w=e=>{if(!u)return;let t=(e,t,n)=>C(be(e,t,n),p,m);if(r>=f&&r<e){let e=r-f,n=d.slice(0,e).join(``),i=d[e]||` `,a=d.slice(e+1).join(``);n&&t(``,R(e)+l,n),t(`term-cursor`,L(l),i),a&&t(``,R(d.length-e-1)+l,a)}else t(``,R(d.length)+l,u);u=``,d=[]},T=(e,t,n,r,i)=>{C(be(e,t,n),r,i)},E=()=>{S&&=(T(`term-canvas-run`,R(S),x,``),x=``,0)};for(let e=0;e<this.cols;e++){let i=t(e),a=e<n,o=a?i.char:0,s=a?i.width??1:1,h=a?Se(i):``,C=a?i.linkUri:void 0;if(v&&a&&s===1&&e!==r&&!C&&!(i.flags&202)&&(!i.underlineStyle||i.underlineStyle===`none`)&&(o===9600||o===9604||o===9608)){let t=N(i.fg,i.fgRgb),n=N(i.bg,i.bgRgb);if(i.flags&j&&([t,n]=[n,t]),t!==void 0&&(o===9608||n!==void 0)){w(e),v[e]=o===9604?n:t,y[e]=o===9600?n:t,b=!0;let r=i.chars??String.fromCodePoint(o);c(r,e),x+=r,S++,_=!1,f=e+1;continue}}let D=v&&a&&s===1&&e!==r&&!h&&!(i.flags&66)&&!(o>=9600&&o<=9631)?ve(i):void 0;v&&D!==void 0&&(v[e]=D,y[e]=D,b=!0),E();let O=a&&s===0&&e>0&&(t(e-1).width??1)===2;if(_&&!O){let e=Ce(i.fg,i.bg,i.flags,i.fgRgb,i.bgRgb).bg;i.flags&66||g!==void 0&&g!==e?_=!1:g=e}if(a&&s===0){if(w(e),!O){c(` `,e);let t=I(i),n=e===r;T(n?`term-cursor`:``,n?L(t):t,` `,h,C)}l=``,p=``,m=void 0,u=``,d=[],f=e+1}else if(a&&s===2){if(w(e),e+1>=this.cols){c(` `,e);let t=I(i),n=e===r;T(n?`term-cursor`:``,n?L(t):t,` `,h,C),l=``,p=``,m=void 0,u=``,d=[],f=e+1;continue}let t=i.chars??(o>=32?String.fromCodePoint(o):` `);c(t,e,2);let n=I(i),a=r>=e&&r<e+2;T(a?`term-wide term-cursor`:`term-wide`,a?L(n):n,t,h,C),l=``,p=``,m=void 0,u=``,d=[],f=e+2}else if(a&&o>=9600&&o<=9631){w(e);let t=i.chars??String.fromCodePoint(o);c(t,e);let n=Ce(i.fg,i.bg,i.flags,i.fgRgb,i.bgRgb),a=e===r?`term-block term-cursor`:`term-block`,s=ke(o,n.fg,n.bg),g=I(i)+`color:${n.fg};background:${s};`;T(a,e===r?L(g):g,t,h,C),l=``,p=``,m=void 0,u=``,d=[],f=e+1}else{let t=i.chars??(a&&o>=32?String.fromCodePoint(o):` `);c(t,e,1,i.spacerHead===!0);let n=a?I(i,D===void 0):``;if(t.length!==1||t.charCodeAt(0)>126){w(e);let a=e===r,s=V[o],c=s&&t===String.fromCodePoint(o)?s:null,u=c?.className??``;c&&i.flags&ce&&(u+=` term-box-bold`),a&&(u+=u?` term-cursor`:`term-cursor`),T(u,(a?L(n):n)+(c?.style??``),t,h,C),l=``,p=``,m=void 0,f=e+1;continue}n!==l||h!==p?(w(e),l=n,p=h,m=C,u=t,d=[t],f=e):(u+=t,d.push(t))}}w(this.cols),E(),h&&a.push({html:o+`</a>`}),this.updateRowParts(e,a),this.rowText.set(e,s),v&&this.paintCellBand(i,b);let D=_&&g!==A?g??``:``;this.rowBackground.get(e)!==D&&(e.style.background=D,this.rowBackground.set(e,D))}updateRowParts(e,t){let n=this.rowParts.get(e),r=0,i=n?.length??0,a=t.length;if(n){for(;r<i&&r<a&&n[r].html===t[r].html;)r++;for(;i>r&&a>r&&n[i-1].html===t[a-1].html;)i--,a--}if(r===i&&r===a)return;let o=n!==void 0&&i===a;for(let i=r;o&&i<a;i++){let r=e.childNodes[i];o=t[i].opening!==void 0&&t[i].opening===n[i].opening&&r?.childNodes.length===1&&r.firstChild?.nodeType===3}if(o){for(let i=r;i<a;i++)t[i].html!==n[i].html&&(e.childNodes[i].firstChild.nodeValue=t[i].text);this.rowParts.set(e,t)}else{if(r+t.length-a<Math.max(i-r,a-r))e.innerHTML=t.map(e=>e.html).join(``);else{let n=e.ownerDocument.createRange();n.setStart(e,r),n.setEnd(e,i),n.deleteContents();let o=t.slice(r,a).map(e=>e.html).join(``);o&&n.insertNode(n.createContextualFragment(o))}this.rowParts.set(e,t)}}_updateScrollbackRow(e,t,n){let r=e.getScrollbackLineLen(t);this._buildRowContent(n,n=>e.getScrollbackCell(t,n),r,-1,-1);let i=this.rowText.get(n),a=e.getScrollbackRowMetadata?.(t);i.metadata=a&&r<=this.cols?{...a}:null}syncScrollback(e,t){let n=e.getScrollbackCount(),r=t?.rowHeight??0,i=t!==void 0&&r>0,a=t?.overscanRows??me,o=t?.scrollbackDiscardedCount!==void 0,s=t?.scrollbackDiscardedCount??0,c=t&&t.clientHeight>0?t.clientHeight:this.rows*r,l=i?Math.floor(t.scrollTop/r):0,u=i?Math.ceil(c/r):n,d=i?Math.max(0,Math.min(n,l-a)):0,f=i?Math.max(d,Math.min(n,l+u+a)):n,p=b(this.container.ownerDocument)?this.container.ownerDocument.getSelection():null,m=p!==null&&!p.isCollapsed&&(this.container.contains(p.anchorNode)||this.container.contains(p.focusNode)),h=this.painted&&!this.colorsChanged&&o&&n===this._renderedScrollbackCount&&s===this._renderedDiscardedCount,g=(this._scrollbackKeys[0]??1/0)-s,_=(this._scrollbackKeys[this._scrollbackKeys.length-1]??-1/0)-s+1,v=Math.ceil(a/2);if(i&&h&&!m&&!t?.selectedRows&&r===this._scrollbackRowHeight&&this._scrollbackKeys.length===_-g&&this._scrollbackKeys.length<=u+2*a&&g<=Math.max(0,Math.min(n,l-v))&&_>=Math.min(n,l+u+v))return;let y=new Set;for(let e=d;e<f;e++)y.add(e);if(!t?.selectedRows&&m&&p.rangeCount===1){let e=p.getRangeAt(0),t=this._scrollbackRowEls.flatMap((t,n)=>e.intersectsNode(t)?[this._scrollbackKeys[n]-s]:[]);if(t.length<=k)for(let e of t)e>=0&&e<n&&y.add(e)}if(t?.selectedRows)for(let e=Math.max(0,t.selectedRows.start);e<=Math.min(n-1,t.selectedRows.end);e++)y.add(e);let x=Array.from(y).sort((e,t)=>e-t),S=x.map(e=>s+e);if(h&&r===this._scrollbackRowHeight&&S.length===this._scrollbackKeys.length&&S.every((e,t)=>e===this._scrollbackKeys[t]))return;let C=new Map;for(let e=0;e<this._scrollbackRowEls.length;e++)C.set(this._scrollbackKeys[e],this._scrollbackRowEls[e]);let w=new Set(S);for(let[e,t]of C)w.has(e)||t.remove();for(let e of this._scrollbackGapSpacers)e.remove();this._scrollbackGapSpacers=[];let T=[],E=this._scrollbackTopSpacer?.nextSibling??null,D=(x[0]??n)-1;for(let t of x){if(t>D+1){let e=document.createElement(`div`);e.className=`term-scrollback-spacer`,e.style.height=`${(t-D-1)*r}px`,this.container.insertBefore(e,E??this._scrollbackBottomSpacer),this._scrollbackGapSpacers.push(e)}D=t;let i=s+t,a=n-1-t,o=C.get(i);o?h||this._updateScrollbackRow(e,a,o):(o=document.createElement(`div`),o.className=`term-row term-scrollback-row`,this._updateScrollbackRow(e,a,o)),o!==E&&this.container.insertBefore(o,E??this._scrollbackBottomSpacer),E=o.nextSibling,T.push(o)}this._scrollbackRowEls=T,this._scrollbackKeys=S,this._renderedScrollbackCount=n,this._renderedDiscardedCount=s,this._scrollbackRowHeight=r,this._scrollbackTopSpacer&&(this._scrollbackTopSpacer.style.height=`${(x[0]??n)*r}px`),this._scrollbackBottomSpacer&&(this._scrollbackBottomSpacer.style.height=`${x.length?(n-x[x.length-1]-1)*r:0}px`)}syncColorOverrides(e={}){for(let[t,n]of[[`foreground`,`--term-app-fg`],[`background`,`--term-app-bg`],[`cursor`,`--term-app-cursor`]]){let r=e[t],i=r===void 0?``:M(r);this.colorHost.style.getPropertyValue(n)!==i&&(i?this.colorHost.style.setProperty(n,i):this.colorHost.style.removeProperty(n))}}syncLiveRows(e){let t=e.getRowId?Array.from({length:this.rows},(t,n)=>e.getRowId(n)):[],n=this.rowIds;if(this.rowIds=t.includes(null)?[]:t,!this.rowIds.length)return null;if(n.length!==t.length)return new Set(t.map((e,t)=>t));if(t.every((e,t)=>e===n[t]))return null;let r=new Map;for(let e=0;e<n.length;e++)r.set(n[e],e);let i=t.map(e=>r.get(e)??-1),a=new Set(i),o=this.rowEls.map((e,t)=>t).filter(e=>!a.has(e)).reverse(),s=new Set;for(let e=0;e<this.rows;e++)i[e]<0&&(i[e]=o.pop(),s.add(e));this.rowEls=i.map(e=>this.rowEls[e]),this.prevCursorRow=i.indexOf(this.prevCursorRow);let c=i.findIndex((e,t)=>!s.has(t)&&e!==t);if(c>=0&&i[c]>c){let e=this.cellCanvas;for(let t=this.rows-1;t>=0;t--){let n=this.rowEls[t];n.nextSibling!==e&&this.container.insertBefore(n,e),e=n}}else{let e=this._scrollbackBottomSpacer.nextSibling;for(let t of this.rowEls)t!==e&&this.container.insertBefore(t,e),e=t.nextSibling}if(this.cellPixels&&this.cellBandUsed.some(Boolean)){let e=this.cellPixels.slice(),t=this.cellImage.width*this.cellRowHeight;for(let n=0;n<this.rows;n++){let r=i[n]*t;this.cellPixels.set(e.subarray(r,r+t),n*t)}this.cellContext.putImageData(this.cellImage,0,0)}return this.cellBandUsed=i.map(e=>this.cellBandUsed[e]),s}render(e,t){this.syncColorOverrides(e.getColorOverrides?.()),this.viewport=t,this.selection??=new ae(this.container.parentElement??this.container);let n=this.selection.beforeRender(e,this.selectionRows()),r=e.getRows(),i=e.getCols(),a=!1;(this.needsSetup||r!==this.rows||i!==this.cols)&&(this.setup(i,r),this.needsSetup=!1,a=!0),this.syncScrollback(e,t&&{...t,selectedRows:n?{start:n.start.row,end:n.end.row}:void 0}),this.graphics.reconcile(e,{scrollTop:t?.scrollTop??0,clientHeight:t?.clientHeight??0,rowHeight:t?.rowHeight??0,charWidth:t?.charWidth??0,overscanRows:t?.overscanRows??me,scrollbackCount:e.getScrollbackCount()});let o=this.syncCellCanvas(t),s=this.syncLiveRows(e);this.cellCanvas.style.top=`${e.getScrollbackCount()*(t?.rowHeight??0)}px`;let c=e.getCursor(),l=c.visible,u=c.shape??`block`,d=String(c.blinking??!1);this.container.dataset.cursorShape!==u&&(this.container.dataset.cursorShape=u),this.container.dataset.cursorBlink!==d&&(this.container.dataset.cursorBlink=d);let f=c.row!==this.prevCursorRow||c.col!==this.prevCursorCol||l!==this.prevCursorVisible;for(let t=0;t<this.rows;t++){let n=this.colorsChanged||a||o||s?.has(t)||(this.rowIds.length?e.isRowContentDirty?.(t)??e.isDirtyRow(t):e.isDirtyRow(t)),r=t===this.prevCursorRow&&f,i=t===c.row;if(n||r||i&&f){let n=i&&l?c.col:-1;this._buildRowContent(this.rowEls[t],n=>e.getCell(t,n),this.cols,n,t)}let u=this.rowText.get(this.rowEls[t]);if(u){let n=e.getRowMetadata?.(t);u.metadata=n?{...n}:null}}this.prevCursorRow=c.row,this.prevCursorCol=c.col,this.prevCursorVisible=l,e.clearDirty(),this.colorsChanged=!1,this.selection.afterRender(this.selectionRows(),n),this.painted=!0}*searchRows(){for(let e=0;e<this._scrollbackRowEls.length;e++)yield{row:this._scrollbackKeys[e]-Math.max(0,this._renderedDiscardedCount),element:this._scrollbackRowEls[e]};for(let e=0;e<this.rowEls.length;e++)yield{row:Math.max(0,this._renderedScrollbackCount)+e,element:this.rowEls[e]}}getSelectionText(){let e=this.container.parentElement;return e?C(e,this.selectionRows()):null}*selectionRows(){for(let e of this.searchRows()){let t=this.rowText.get(e.element);t&&(yield{...e,content:t})}}beforeMutation(e){this.selection?.beforeMutation(e,this.selectionRows()),this.painted=!1}positionAt(e,t,n){if(!this.painted||this.needsSetup||n<=0)return null;let r=e.closest(`.term-row`),i=Array.from(this.searchRows()).find(e=>e.element===r);if(!i)return null;let a=Math.floor((t-i.element.getBoundingClientRect().left)/n);return a>=0&&a<this.cols?{row:i.row,col:a}:null}select(e,t,n,r){if(!this.painted||this.needsSetup)return!1;let i=ne(e,t,n);if(!i||(r(),!this.painted||this.needsSetup))return!1;this.syncScrollback(e,{...this.viewport??{scrollTop:0,clientHeight:0,rowHeight:0},selectedRows:{start:i.start.row,end:i.end.row}});let a=Array.from(this.selectionRows()),o=(e,t)=>{let n=a.find(t=>t.row===e.row);return n&&D(n.element,E(n.content,e.col,t))},s=o(i.start,!1),c=o(i.end,!0),l=this.container.ownerDocument.getSelection();return!s||!c||!l?!1:(x(this.container.ownerDocument),l.setBaseAndExtent(...s,...c),this.selection?.capture(e,this.selectionRows()),!0)}rectangle(e,t,n,r){if(!this.painted||this.needsSetup)return null;let i=ie(e,t,n);return i?(r(),this.painted&&!this.needsSetup?i:null):null}dragPositionAt(e,t,n){if(!this.painted||this.needsSetup||n<=0)return null;let r=null;for(let{row:i,element:a}of this.searchRows()){let o=a.getBoundingClientRect(),s=Math.max(o.top-t,t-o.bottom,0);(!r||s<r.distance)&&(r={row:i,distance:s,col:Math.max(0,Math.min(this.cols-1,Math.floor((e-o.left)/n)))})}return r&&{row:r.row,col:r.col}}setCanvasSuspended(e){this.cellSuspended=e}requestSetup(){this.needsSetup=!0}invalidateColors(){this.colorsChanged=!0}setSearchDecorations(e){(e.firstChild||this.searchLayer.firstChild)&&this.searchLayer.replaceChildren(e)}destroy(){this.syncColorOverrides(),this.painted=!1,this.selection?.dispose(),this.graphics.destroy(),this.container.innerHTML=``,this.rowEls=[],this._scrollbackRowEls=[],this.cellImage=null,this.cellPixels=null,this.cellContext=null}},Fe=[`aria-label`,`aria-labelledby`,`aria-describedby`,`aria-description`],Ie=`Press Escape, then Tab to move focus out of the terminal, or Shift+Tab to move focus backward.`,Le=0,Re=class{constructor(e,t){this.host=e,this.input=t,this.destroyed=!1,this.hint=e.ownerDocument.createElement(`span`);do this.hint.id=`wterm-input-help-${++Le}`;while(e.getRootNode().querySelector(`#${this.hint.id}`));this.hint.hidden=!0,this.hint.textContent=Ie,e.append(this.hint),this.tabIndex=e.getAttribute(`tabindex`),this.defaultRole=!e.hasAttribute(`role`),this.defaultRole&&e.setAttribute(`role`,`group`),this.observer=new MutationObserver(e=>this.sync(e)),this.sync()}sync(e=[]){e.some(e=>e.attributeName===`tabindex`)&&(this.tabIndex=this.host.getAttribute(`tabindex`));for(let e of Fe){let t=this.host.getAttribute(e);t?.trim()?this.input.setAttribute(e,t):this.input.removeAttribute(e)}this.input.hasAttribute(`aria-label`)||this.input.setAttribute(`aria-label`,`Terminal`);let t=this.input.getAttribute(`aria-describedby`);t&&this.input.setAttribute(`aria-describedby`,`${t} ${this.hint.id}`),this.input.setAttribute(`aria-description`,[this.input.getAttribute(`aria-description`),Ie].filter(Boolean).join(` `)),this.input.setAttribute(`tabindex`,this.tabIndex??`0`),this.observer.disconnect(),this.tabIndex!==null&&this.host.setAttribute(`tabindex`,`-1`),this.observer.observe(this.host,{attributes:!0,attributeFilter:[...Fe,`tabindex`]})}destroy(){this.destroyed||(this.destroyed=!0,this.observer.takeRecords().some(e=>e.attributeName===`tabindex`)&&(this.tabIndex=this.host.getAttribute(`tabindex`)),this.observer.disconnect(),this.hint.remove(),this.tabIndex===null?this.host.removeAttribute(`tabindex`):this.host.setAttribute(`tabindex`,this.tabIndex),this.defaultRole&&this.host.getAttribute(`role`)===`group`&&this.host.removeAttribute(`role`))}};function H(e,t){return t.platform.startsWith(`Mac`)?e.metaKey:e.ctrlKey}var U={Escape:{code:27,final:`u`},Enter:{code:13,final:`u`},Tab:{code:9,final:`u`},Backspace:{code:127,final:`u`},Insert:{code:2,final:`~`},Delete:{code:3,final:`~`},ArrowLeft:{code:1,final:`D`},ArrowRight:{code:1,final:`C`},ArrowUp:{code:1,final:`A`},ArrowDown:{code:1,final:`B`},PageUp:{code:5,final:`~`},PageDown:{code:6,final:`~`},Home:{code:1,final:`H`},End:{code:1,final:`F`},CapsLock:{code:57358,final:`u`,modifier:!0},ScrollLock:{code:57359,final:`u`},NumLock:{code:57360,final:`u`,modifier:!0},PrintScreen:{code:57361,final:`u`},Pause:{code:57362,final:`u`},F1:{code:1,final:`P`},F2:{code:1,final:`Q`},F3:{code:13,final:`~`},F4:{code:1,final:`S`},F5:{code:15,final:`~`},F6:{code:17,final:`~`},F7:{code:18,final:`~`},F8:{code:19,final:`~`},F9:{code:20,final:`~`},F10:{code:21,final:`~`},F11:{code:23,final:`~`},F12:{code:24,final:`~`},ShiftLeft:{code:57441,final:`u`,modifier:!0},ControlLeft:{code:57442,final:`u`,modifier:!0},AltLeft:{code:57443,final:`u`,modifier:!0},MetaLeft:{code:57444,final:`u`,modifier:!0},ShiftRight:{code:57447,final:`u`,modifier:!0},ControlRight:{code:57448,final:`u`,modifier:!0},AltRight:{code:57449,final:`u`,modifier:!0},MetaRight:{code:57450,final:`u`,modifier:!0},Numpad0:{code:57399,final:`u`},Numpad1:{code:57400,final:`u`},Numpad2:{code:57401,final:`u`},Numpad3:{code:57402,final:`u`},Numpad4:{code:57403,final:`u`},Numpad5:{code:57404,final:`u`},Numpad6:{code:57405,final:`u`},Numpad7:{code:57406,final:`u`},Numpad8:{code:57407,final:`u`},Numpad9:{code:57408,final:`u`},NumpadDecimal:{code:57409,final:`u`},NumpadDivide:{code:57410,final:`u`},NumpadMultiply:{code:57411,final:`u`},NumpadSubtract:{code:57412,final:`u`},NumpadAdd:{code:57413,final:`u`},NumpadEnter:{code:57414,final:`u`},NumpadEqual:{code:57415,final:`u`},NumpadComma:{code:57416,final:`u`}},ze={code:1,final:`E`};for(let e=13;e<=25;e++)U[`F${e}`]={code:57363+e,final:`u`};function W(e){let t=Array.from(e);return t.length===1?t[0].codePointAt(0):null}function G(e){let t=W(e.key);return t===null||t<32||t===127?null:{code:W(e.key.toLowerCase())??t,final:`u`}}function Be(e,t){if(t&&e.code.startsWith(`Numpad`)){if(e.code===`Numpad5`&&e.key===`Clear`)return{entry:ze,functionalKey:`Begin`};if(e.key.length===1){let t=G(e);return t?{entry:t,functionalKey:null}:null}let t=U[e.key];return t?{entry:t,functionalKey:e.key}:null}let n=Ve(e);if(n)return{entry:n,functionalKey:e.code};let r=U[e.code];if(r)return{entry:r,functionalKey:e.code};let i=U[e.key];if(i)return{entry:i,functionalKey:e.key};let a=G(e);return a?{entry:a,functionalKey:null}:null}function Ve(e){let t={"Numpad4:ArrowLeft":57417,"Numpad6:ArrowRight":57418,"Numpad8:ArrowUp":57419,"Numpad2:ArrowDown":57420,"Numpad9:PageUp":57421,"Numpad3:PageDown":57422,"Numpad7:Home":57423,"Numpad1:End":57424,"Numpad0:Insert":57425,"NumpadDecimal:Delete":57426,"Numpad5:Clear":57427}[`${e.code}:${e.key}`];return t===void 0?null:{code:t,final:`u`}}function K(e,t){for(let n of t??[])if(n.startsWith(e))return!0;return!1}function He(e,t,n){let r=1,i=t!==`release`;return(e.shiftKey||K(`Shift`,n)||i&&e.code.startsWith(`Shift`))&&(r+=1),(e.altKey||K(`Alt`,n)||i&&e.code.startsWith(`Alt`))&&(r+=2),(e.ctrlKey||K(`Control`,n)||i&&e.code.startsWith(`Control`))&&(r+=4),(e.metaKey||K(`Meta`,n)||i&&e.code.startsWith(`Meta`))&&(r+=8),e.getModifierState(`CapsLock`)&&(r+=64),e.getModifierState(`NumLock`)&&(r+=128),r}function Ue(e){return e.ctrlKey||e.metaKey||e.altKey?[]:Array.from(e.key).map(e=>e.codePointAt(0)).filter(e=>e>=32&&e!==127)}function We(e){if(e.length!==1)return null;let t=e.toLowerCase().charCodeAt(0);if(t>=97&&t<=122)return String.fromCharCode(t-96);switch(e){case` `:case`2`:case`@`:return`\0`;case`3`:case`[`:return`\x1B`;case`4`:case`\\`:return``;case`5`:case`]`:return``;case`6`:case`^`:case`~`:return``;case`7`:case`/`:case`_`:return``;case`8`:case`?`:return``;default:return null}}function Ge(e){if(e.metaKey)return null;let t=Array.from(e.key);if(t.length!==1||t[0].codePointAt(0)<32||t[0].codePointAt(0)>126||e.shiftKey&&e.ctrlKey&&/^[a-z]$/i.test(e.key))return null;if(e.ctrlKey){let t=e.key.toLowerCase(),n=We(t)??t;return e.altKey?`\x1b${n}`:n}return e.altKey?`\x1b${e.key}`:null}function Ke(e,t,n,r,i){let a=!!(t&1),o=!!(t&2),s=!!(t&8),c=!a&&!o&&!s,l=r&-193;if(i&&c&&l===0){let t={ArrowUp:`\x1BOA`,ArrowDown:`\x1BOB`,ArrowRight:`\x1BOC`,ArrowLeft:`\x1BOD`,Begin:`\x1BOE`,End:`\x1BOF`,Home:`\x1BOH`}[e];if(t)return{handled:!0,sequence:t}}if(l===0){if(!a&&!s&&e===`Escape`)return{handled:!0,sequence:`\x1B`};if(c){let t={F1:`\x1BOP`,F2:`\x1BOQ`,F3:`\x1BOR`,F4:`\x1BOS`}[e];if(t)return{handled:!0,sequence:t}}}if(c&&r!==0){let t=r&2?`\x1B`:``;if(e===`Enter`)return{handled:!0,sequence:`${t}\r`};if(e===`Escape`)return{handled:!0,sequence:`${t}\x1b`};if(e===`Backspace`)return{handled:!0,sequence:`${t}${r&4?`\b`:``}`};if(e===`Tab`)return r&1?{handled:!0,sequence:`${r&2?`\x1B\x1B`:`\x1B`}[Z`}:{handled:!0,sequence:`${t}\t`}}return l===0&&!s&&(e===`Enter`||e===`Backspace`||e===`Tab`)?{handled:!0,sequence:n===`release`?null:e===`Enter`?`\r`:e===`Backspace`?``:` `}:{handled:!1,sequence:null}}function q(e,t,n,r,i=!1){if(t===0||n===`release`&&!(t&2))return null;let a=!(t&1)&&!(t&8),o=Be(e,a),s=o?.entry??null,c=G(e),l=!(t&8)&&c!==null&&!e.altKey&&!e.ctrlKey&&!e.metaKey,u=!(t&1)&&!(t&8)&&(n===`press`||!(t&2))&&(e.ctrlKey||e.altKey)?Ge(e):null;if(n===`release`&&!(t&8)&&l)return null;if(n!==`release`&&!(t&8)&&!e.altKey&&!e.ctrlKey&&!e.metaKey){if(!e.shiftKey){if(e.key===`Enter`&&(e.code!==`NumpadEnter`||a))return`\r`;if(e.key===`Tab`)return` `;if(e.key===`Backspace`)return``}if(l)return e.key}if(u!==null)return u;if(!s||s.modifier&&!(t&8))return null;let d=He(e,n,r);if(o?.functionalKey){let e=Ke(o.functionalKey,t,n,d-1,i);if(e.handled)return e.sequence}let f=t&2?n===`repeat`?2:n===`release`?3:0:0;if(s.final!==`u`&&s.final!==`~`)return f===0?d>1?`\x1b[1;${d}${s.final}`:`\x1b[${s.final}`:`\x1b[1;${d}:${f}${s.final}`;let p=`\x1b[${s.code}`;if(c&&t&4&&e.shiftKey){let t=W(e.key);t!==null&&t!==s.code&&(p+=`:${t}`)}let m=!1;if(f===2||f===3?(p+=`;${d}:${f}`,m=!0):d>1&&(p+=`;${d}`,m=!0),c&&t&16&&n!==`release`){let t=Ue(e);t.length>0&&(p+=m?`;`:`;;`,p+=t.join(`:`))}return p+s.final}var qe={ArrowUp:`\x1B[A`,ArrowDown:`\x1B[B`,ArrowRight:`\x1B[C`,ArrowLeft:`\x1B[D`,Home:`\x1B[H`,End:`\x1B[F`},Je={ArrowUp:`\x1BOA`,ArrowDown:`\x1BOB`,ArrowRight:`\x1BOC`,ArrowLeft:`\x1BOD`,Home:`\x1BOH`,End:`\x1BOF`},Ye={ArrowUp:`A`,ArrowDown:`B`,ArrowRight:`C`,ArrowLeft:`D`,Home:`H`,End:`F`,F1:`P`,F2:`Q`,F3:`R`,F4:`S`},Xe={Insert:2,Delete:3,PageUp:5,PageDown:6,F5:15,F6:17,F7:18,F8:19,F9:20,F10:21,F11:23,F12:24},Ze={Enter:`\r`,Backspace:``,Tab:` `,Escape:`\x1B`,Insert:`\x1B[2~`,Delete:`\x1B[3~`,PageUp:`\x1B[5~`,PageDown:`\x1B[6~`,F1:`\x1BOP`,F2:`\x1BOQ`,F3:`\x1BOR`,F4:`\x1BOS`,F5:`\x1B[15~`,F6:`\x1B[17~`,F7:`\x1B[18~`,F8:`\x1B[19~`,F9:`\x1B[20~`,F10:`\x1B[21~`,F11:`\x1B[23~`,F12:`\x1B[24~`},Qe=250,$e=5,J=``;function et(e,t){if(e.metaKey||!(e.getModifierState(`AltGraph`)||e.ctrlKey&&e.altKey&&t.has(`AltRight`)))return!1;let n=Array.from(e.key);return n.length===1&&n[0].codePointAt(0)>=32&&n[0]!==``}var tt=class{constructor(e,t,n,r=()=>null,i=()=>{},a,o){this.selectionActions=o,this.composing=!1,this.compositionWidth=0,this.recentCompositionCommit=null,this.suppressNextTouchDeleteInput=!1,this.mouseButtons=0,this.lastMouseMotion=null,this.focused=!1,this.suppressedKeyUps=new Set,this.pressedModifiers=new Set,this.deliveredKeys=new Set,this.tabExitArmed=!1,this.element=e,this.onData=t,this.onBinary=a,this.getBridge=n,this.getCellSize=r,this.prepareComposition=i,this.touchPrimary=e.ownerDocument.defaultView?.matchMedia?.(`(pointer: coarse)`).matches??!1,this.textarea=document.createElement(`textarea`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`autocomplete`,`off`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.setAttribute(`enterkeyhint`,`send`),this.textarea.wrap=`off`;let s=this.textarea.style;s.position=`absolute`,s.left=`-9999px`,s.top=`0`,s.width=this.touchPrimary?`var(--term-cell-width, 1ch)`:`1px`,s.height=this.touchPrimary?`var(--term-row-height)`:`1px`,s.boxSizing=`border-box`,s.font=`inherit`,s.lineHeight=`var(--term-row-height)`,s.fontKerning=`none`,s.fontVariantLigatures=`none`,s.whiteSpace=`pre`,s.zIndex=`2`,s.opacity=this.touchPrimary?`1`:`0`,s.overflow=`hidden`,s.border=`0`,s.padding=`0`,s.margin=`0`,s.outline=`none`,s.resize=`none`,s.pointerEvents=this.touchPrimary?`auto`:`none`,s.caretColor=`transparent`,s.color=`transparent`,s.background=`transparent`,e.appendChild(this.textarea),this.accessibility=new Re(e,this.textarea),this._onKeyDown=this.handleKeyDown.bind(this),this._onKeyUp=this.handleKeyUp.bind(this),this._onPaste=this.handlePaste.bind(this),this._onCompositionStart=this.handleCompositionStart.bind(this),this._onCompositionEnd=this.handleCompositionEnd.bind(this),this._onInput=this.handleInput.bind(this),this._onFocus=()=>{this.focused||(this.focused=!0,this.touchPrimary&&!this.textarea.value&&this.resetInputValue(),this.positionTextarea(),this.element.classList.add(`focused`),this.getBridge()?.focusEvents?.()&&this.onData(`\x1B[I`))},this._onBlur=()=>{this.tabExitArmed=!1,this.focused=!1,this.composing=!1,this.recentCompositionCommit=null,this.suppressNextTouchDeleteInput=!1,this.hideComposition(),this.textarea.value=``,this.element.classList.remove(`focused`),this.stopMouseCapture(),this.lastMouseMotion=null,this.pressedModifiers.clear(),this.deliveredKeys.clear(),this.getBridge()?.focusEvents?.()&&this.onData(`\x1B[O`)},this._onMouseDown=e=>{this.tabExitArmed=!1,this.handleMouse(e,`press`)},this._onHoverMove=e=>{this.mouseButtons===0&&(e.buttons!==0||e.shiftKey?this.lastMouseMotion=null:this.handleMouse(e,`move`))},this._onMouseMove=e=>{this.mouseButtons!==0&&this.handleMouse(e,`move`)},this._onMouseUp=e=>{this.mouseButtons!==0&&(this.handleMouse(e,`release`),this.mouseButtons=e.buttons&7,this.mouseButtons===0&&this.stopMouseCapture())},this._onMouseLeave=()=>{this.mouseButtons===0&&(this.lastMouseMotion=null)},this._onWheel=e=>this.handleMouse(e,`wheel`),this.textarea.addEventListener(`keydown`,this._onKeyDown),this.textarea.addEventListener(`keyup`,this._onKeyUp),this.textarea.addEventListener(`paste`,this._onPaste),this.textarea.addEventListener(`compositionstart`,this._onCompositionStart),this.textarea.addEventListener(`compositionend`,this._onCompositionEnd),this.textarea.addEventListener(`input`,this._onInput),this.textarea.addEventListener(`focus`,this._onFocus),this.textarea.addEventListener(`blur`,this._onBlur),this.element.addEventListener(`mousedown`,this._onMouseDown),this.element.addEventListener(`mousemove`,this._onHoverMove),this.element.addEventListener(`mouseleave`,this._onMouseLeave),this.element.addEventListener(`wheel`,this._onWheel,{passive:!1})}focus(){this.touchPrimary&&this.prepareComposition(),this.touchPrimary&&!this.composing&&!this.textarea.value&&this.resetInputValue(),this.positionTextarea(),this.textarea.focus({preventScroll:!0})}syncInputPosition(){(this.composing||this.touchPrimary)&&this.positionTextarea()}destroy(){this.accessibility.destroy(),this.textarea.removeEventListener(`keydown`,this._onKeyDown),this.textarea.removeEventListener(`keyup`,this._onKeyUp),this.textarea.removeEventListener(`paste`,this._onPaste),this.textarea.removeEventListener(`compositionstart`,this._onCompositionStart),this.textarea.removeEventListener(`compositionend`,this._onCompositionEnd),this.textarea.removeEventListener(`input`,this._onInput),this.textarea.removeEventListener(`focus`,this._onFocus),this.textarea.removeEventListener(`blur`,this._onBlur),this.element.removeEventListener(`mousedown`,this._onMouseDown),this.element.removeEventListener(`mousemove`,this._onHoverMove),this.element.removeEventListener(`mouseleave`,this._onMouseLeave),this.stopMouseCapture(),this.element.removeEventListener(`wheel`,this._onWheel),this.element.classList.remove(`focused`),this.textarea.remove()}handleKeyDown(e){let t=e.code||e.key;e.key!==`Backspace`&&(this.suppressNextTouchDeleteInput=!1);let n=/^(Shift|Control|Alt|Meta)(Left|Right)$/.test(e.code);if(n&&this.pressedModifiers.add(e.code),this.composing||e.isComposing||e.keyCode===229){this.tabExitArmed=!1,this.positionTextarea(),this.suppressedKeyUps.add(t);return}this.recentCompositionCommit=null;let r=this.getBridge(),i=r?.kittyKeyboardFlags?.()??0,a=n&&!!(i&8),o=this.deliveredKeys.has(t);if(this.tabExitArmed&&e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.repeat&&!o){this.tabExitArmed=!1,this.suppressedKeyUps.add(t);return}if((e.key!==`Shift`||e.altKey||e.ctrlKey||e.metaKey)&&(this.tabExitArmed=e.key===`Escape`&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey),et(e,this.pressedModifiers)){o||this.suppressedKeyUps.add(t);return}if(!o&&this.selectionActions&&!e.altKey&&(e.metaKey&&!e.ctrlKey&&!e.shiftKey||e.ctrlKey&&e.shiftKey&&!e.metaKey)&&e.key.toLowerCase()===`a`){e.preventDefault(),e.stopPropagation(),this.suppressedKeyUps.add(t),this.selectionActions.selectAll();return}if(!o&&e.key===`Escape`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&this.selectionActions?.hasSelection()){e.preventDefault(),e.stopPropagation(),this.suppressedKeyUps.add(t),this.selectionActions.clearSelection();return}if(!o&&(e.metaKey||e.ctrlKey)&&!e.altKey&&e.key.toLowerCase()===`c`){let n=window.getSelection();if(this.selectionActions?.hasSelection()||n&&n.toString().length>0){this.suppressedKeyUps.add(t),e.ctrlKey&&e.shiftKey&&!e.metaKey&&(e.preventDefault(),e.stopPropagation(),this.element.ownerDocument.execCommand(`copy`));return}}if(!o&&(e.metaKey||e.ctrlKey)&&e.key===`v`){this.suppressedKeyUps.add(t),this.textarea.focus();return}if(!o&&!a&&e.metaKey&&!e.ctrlKey){if(this.suppressedKeyUps.add(t),e.key===`Backspace`)e.preventDefault(),this.selectionActions?.clearSelection(),this.onData(``);else if(e.key===`a`){e.preventDefault();let t=this.element.ownerDocument,n=t.getSelection();if(n){let e=t.createRange();e.selectNodeContents(this.element),x(t),n.removeAllRanges(),n.addRange(e)}}return}this.suppressedKeyUps.delete(t);let s=this.touchPrimary&&e.key===`Backspace`&&!e.altKey&&!e.ctrlKey&&!e.metaKey;if(i!==0){let a=q(e,i,e.repeat?`repeat`:`press`,this.pressedModifiers,r?.cursorKeysApp?.()??!1);a&&(n||this.selectionActions?.clearSelection(),s?this.suppressNextTouchDeleteInput=!0:e.preventDefault(),e.stopPropagation(),this.deliveredKeys.add(t),this.onData(a,n));return}let c=this.keyToSequence(e);c&&(this.selectionActions?.clearSelection(),s?this.suppressNextTouchDeleteInput=!0:e.preventDefault(),e.stopPropagation(),this.onData(c))}handleKeyUp(e){let t=e.code||e.key;this.pressedModifiers.delete(e.code);let n=this.deliveredKeys.delete(t);if(this.suppressedKeyUps.delete(t)||!n||this.composing)return;let r=this.getBridge(),i=r?.kittyKeyboardFlags?.()??0;if(!(i&2))return;let a=q(e,i,`release`,this.pressedModifiers,r?.cursorKeysApp?.()??!1);a&&(e.preventDefault(),this.onData(a,!0))}handlePaste(e){this.tabExitArmed=!1,this.recentCompositionCommit=null,this.suppressNextTouchDeleteInput=!1;let t=e.clipboardData?.getData(`text`);t&&(e.preventDefault(),this.sendPaste(t))}sendPaste(e){this.selectionActions?.clearSelection();let t=this.getBridge();if(t&&t.bracketedPaste()){let t=e.replace(/\x1b/g,``);this.onData(`\x1B[200~`+t+`\x1B[201~`)}else this.onData(e)}handleCompositionStart(){this.tabExitArmed=!1,this.prepareComposition(),this.composing=!0,this.recentCompositionCommit=null,this.suppressNextTouchDeleteInput=!1,this.touchPrimary&&this.textarea.value===J&&(this.textarea.value=``),this.positionTextarea();let e=this.textarea.style;e.opacity=`1`,e.color=`var(--term-fg, currentColor)`,e.background=`var(--term-bg, transparent)`,e.caretColor=`var(--term-fg, currentColor)`}handleCompositionEnd(e){this.composing=!1,this.hideComposition(),this.resetInputValue(),e.data&&(this.recentCompositionCommit={text:e.data,at:performance.now()},this.onData(e.data))}hideComposition(){this.compositionWidth=0;let e=this.textarea.style;e.opacity=this.touchPrimary?`1`:`0`,e.width=this.touchPrimary?`var(--term-cell-width, 1ch)`:`1px`,e.height=this.touchPrimary?`var(--term-row-height)`:`1px`,e.color=`transparent`,e.background=`transparent`,e.caretColor=`transparent`}positionTextarea(){let e=this.getBridge(),t=this.getCellSize(),n=this.element.querySelector(`.term-row:not(.term-scrollback-row)`);if(!e||!t||!n||!e.getCursor){this.textarea.style.left=`0px`,this.textarea.style.top=`0px`,this.composing&&(this.textarea.style.width=`${Math.max(1,this.compositionWidth)}px`,this.textarea.style.height=`${t?.rowHeight??17}px`);return}let{charWidth:r,rowHeight:i}=t;if(r<=0||i<=0)return;let a=e.getCursor(),o=Math.max(0,Math.min(a.col,e.getCols()-1)),s=Math.max(0,Math.min(a.row,e.getRows()-1)),c=this.element.getBoundingClientRect(),l=n.getBoundingClientRect(),u=this.textarea.style;u.left=`${l.left-c.left-this.element.clientLeft+this.element.scrollLeft+o*r}px`,u.top=`${l.top-c.top-this.element.clientTop+this.element.scrollTop+s*i}px`,this.composing&&(u.width=`${Math.min((e.getCols()-o)*r,Math.max(r,this.compositionWidth))}px`,u.height=`${i}px`)}sizeComposition(){let e=this.getCellSize()?.charWidth;!e||e<=0||(this.textarea.style.width=`1px`,this.compositionWidth=this.textarea.value?Math.max(e,this.textarea.scrollWidth+e):e,this.positionTextarea())}resetInputValue(){this.textarea.value=this.touchPrimary?J:``,this.touchPrimary&&this.textarea.setSelectionRange(1,1)}sendTouchDelete(){this.selectionActions?.clearSelection();let e=this.getBridge(),t=e?.kittyKeyboardFlags?.()??0,n=t?q(new KeyboardEvent(`keydown`,{key:`Backspace`,code:`Backspace`}),t,`press`,void 0,e?.cursorKeysApp?.()??!1):``;n&&this.onData(n)}handleInput(e){if(this.tabExitArmed=!1,this.composing){this.sizeComposition();return}let t=e.inputType,n=this.textarea.value,r=this.touchPrimary&&n.startsWith(J)?n.slice(1):n;this.resetInputValue();let i=this.recentCompositionCommit;this.recentCompositionCommit=null,this.touchPrimary&&t===`deleteContentBackward`?this.suppressNextTouchDeleteInput?this.suppressNextTouchDeleteInput=!1:this.sendTouchDelete():(this.suppressNextTouchDeleteInput=!1,r&&(i&&r===i.text&&performance.now()-i.at<Qe||(t===`insertFromPaste`?this.sendPaste(r):(this.selectionActions?.clearSelection(),this.onData(r)))))}handleMouse(e,t){let n=this.getBridge(),r=n?.mouseTracking?.()??0,i=n?.mouseEncoding?.()??(n?.mouseSgr?.()?`sgr`:null);if(!n||r===0||i!==`sgr`&&i!==`sgr-pixels`&&i!==`x10`&&i!==`utf8`&&i!==`urxvt`){this.lastMouseMotion=null;return}if(t===`wheel`){let t=e,n=this.element.scrollHeight-this.element.clientHeight;if(n>0&&(t.shiftKey||n-this.element.scrollTop>$e)){if(this.lastMouseMotion=null,t.shiftKey){let e=Math.abs(t.deltaX)>Math.abs(t.deltaY)?t.deltaX:t.deltaY,n=t.deltaMode===1?this.getCellSize()?.rowHeight??16:t.deltaMode===2?this.element.clientHeight:1;e!==0&&(this.element.scrollTop+=e*n,t.preventDefault())}return}}if(t===`press`&&H(e,this.element.ownerDocument.defaultView?.navigator??navigator)&&e.target instanceof Element&&e.target.closest(`.term-link`)||t===`press`&&(e.shiftKey||e.button>2)||t===`release`&&e.button>2)return;let a=e.buttons&7;if(t===`move`&&!(r===1003||r===1002&&a!==0)){this.lastMouseMotion=null;return}let o=this.element.ownerDocument.defaultView;if(!o)return;let s=this.element.querySelector(`.term-row:not(.term-scrollback-row)`),c=this.element.getBoundingClientRect(),l=s?.getBoundingClientRect(),u=this.getCellSize(),d,f,p,m;if(l&&u)d=l.left,f=l.top,p=u.charWidth,m=u.rowHeight;else{let e=o.getComputedStyle(this.element),t=parseFloat(e.borderLeftWidth)||0,r=parseFloat(e.borderRightWidth)||0,i=parseFloat(e.borderTopWidth)||0,a=parseFloat(e.borderBottomWidth)||0,s=parseFloat(e.paddingLeft)||0,u=parseFloat(e.paddingRight)||0,h=parseFloat(e.paddingTop)||0,g=parseFloat(e.paddingBottom)||0;d=l?.left??c.left+t+s,f=l?.top??c.top+i+h,p=(c.width-t-r-s-u)/n.getCols(),m=(c.height-i-a-h-g)/n.getRows()}let h=n.getCols(),g=n.getRows(),_=p*h,v=m*g;if(!Number.isFinite(_)||!Number.isFinite(v)||_<=0||v<=0)return;if((e.clientX<d||e.clientX>=d+_||e.clientY<f||e.clientY>=f+v)&&(t===`press`||t===`wheel`||t===`move`&&a===0)){this.lastMouseMotion=null;return}let y=i===`sgr-pixels`,b=Math.max(1,Math.min(y?Math.ceil(_):h,Math.floor((e.clientX-d)/(y?1:p))+1)),x=Math.max(1,Math.min(y?Math.ceil(v):g,Math.floor((e.clientY-f)/(y?1:m))+1)),S=(e.shiftKey?4:0)|(e.altKey?8:0)|(e.ctrlKey?16:0),C,w=`M`;if(t===`wheel`){let t=e;if(Math.abs(t.deltaX)>Math.abs(t.deltaY)){if(t.deltaX===0)return;C=(t.deltaX<0?66:67)|S}else{if(t.deltaY===0)return;C=(t.deltaY<0?64:65)|S}}else C=(t===`release`&&i!==`sgr`&&!y?3:t===`move`?a===0?3:a&4?1:a&2?2:0:e.button===1?1:e.button===2?2:0)|S|(t===`move`?32:0),t===`release`&&(w=`m`);let T=i===`x10`?Uint8Array.of(27,91,77,C+32,b+32,x+32):null;if(T&&(b>223||x>223||!this.onBinary&&(T[4]>127||T[5]>127)))this.lastMouseMotion=null;else if(i===`utf8`&&(b>2015||x>2015))this.lastMouseMotion=null;else{if(t===`move`){let e=this.lastMouseMotion;if(e?.mode===r&&e.encoding===i&&e.code===C&&e.x===b&&e.y===x)return;this.lastMouseMotion={mode:r,encoding:i,code:C,x:b,y:x}}else this.lastMouseMotion=null;t===`press`&&(this.textarea.focus({preventScroll:!0}),this.focused||this._onFocus(),this.mouseButtons=a||(e.button===1?4:e.button===2?2:1),o.addEventListener(`mousemove`,this._onMouseMove),o.addEventListener(`mouseup`,this._onMouseUp)),e.preventDefault(),T?this.onBinary?this.onBinary(T):this.onData(String.fromCharCode(...T)):i===`utf8`?this.onData(`\x1b[M${String.fromCodePoint(C+32,b+32,x+32)}`):i===`urxvt`?this.onData(`\x1b[${C+32};${b};${x}M`):this.onData(`\x1b[<${C};${b};${x}${w}`)}}stopMouseCapture(){this.mouseButtons=0;let e=this.element.ownerDocument.defaultView;e?.removeEventListener(`mousemove`,this._onMouseMove),e?.removeEventListener(`mouseup`,this._onMouseUp)}keyToSequence(e){if(e.ctrlKey&&!e.altKey&&!e.metaKey){let t=We(e.key);if(t!==null)return t;if(e.key===`Backspace`)return`\b`}if(e.key===`Enter`&&e.shiftKey)return`\x1B[13;2u`;if(e.key===`Tab`&&e.shiftKey)return`\x1B[Z`;if(!e.metaKey&&(e.shiftKey||e.altKey||e.ctrlKey)){let t=1+Number(e.shiftKey)+2*Number(e.altKey)+4*Number(e.ctrlKey),n=Ye[e.key];if(n)return`\x1b[1;${t}${n}`;let r=Xe[e.key];if(r)return`\x1b[${r};${t}~`}let t=Ze[e.key];if(t)return e.altKey?`\x1B`+t:t;let n=this.getBridge(),r=(n&&n.cursorKeysApp()?Je:qe)[e.key];return r?e.altKey?`\x1B`+r:r:e.key.length===1&&!e.ctrlKey&&!e.metaKey?e.altKey?`\x1B`+e.key:e.key:null}},nt=16777216;function*rt(e,t=nt){let n=e.getScrollbackCount(),r=[],i=``,a=0,o=0,s=!1,c=e=>{if(a+=e.length,a>t)throw RangeError(`Terminal text exceeds 16,777,216 UTF-16 code units`);i+=e,i.length>=8192&&(r.push(i),i=``)};for(let r=0;r<n+e.getRows();r++){let i=n-r-1,l=r<n?e.getScrollbackRowMetadata?.(i):e.getRowMetadata?.(r-n);r>0&&!(s&&l?.continuesPrevious)&&c(`
|
|
4
|
+
`),s=l?.wrapsToNext??!1;let u=r<n?e.getScrollbackLineLen(i):e.getCols(),d=0;for(let s=0;s<u;s++){++o>=256&&(o=0,yield);let l=r<n?e.getScrollbackCell(i,s):e.getCell(r-n,s);if(l.width===0||l.spacerHead)continue;let u=l.chars??String.fromCodePoint(l.char||32);if(/^ +$/.test(u))d+=u.length;else{if(a+d+u.length>t)throw RangeError(`Terminal text exceeds 16,777,216 UTF-16 code units`);c(` `.repeat(d)+u),d=0}}if(s){if(a+d>t)throw RangeError(`Terminal text exceeds 16,777,216 UTF-16 code units`);c(` `.repeat(d))}++o>=256&&(o=0,yield)}return r.push(i),r.join(``)}function it(e){return new DOMException(e,`AbortError`)}var at=class{constructor(){this.request=null,this.timer=null}read(e){return this.cancel(it(`Replaced by another text capture`)),e?.aborted?Promise.reject(e.reason):new Promise((t,n)=>{let r=()=>this.cancel(e?.reason);this.request={resolve:t,reject:n,signal:e,abort:r,scan:null},e?.addEventListener(`abort`,r,{once:!0})})}resume(e){let t=this.request;if(!t||t.scan)return;let n=t.scan=rt(e),r=()=>{if(this.request!==t)return;this.timer=null;let e=performance.now()+4;try{for(let r=0;r<32;r++){let r=n.next();if(r.done){this.release(),t.resolve(r.value);return}if(performance.now()>=e)break}this.timer=setTimeout(r,0)}catch(e){this.cancel(e)}};this.timer=setTimeout(r,0)}cancel(e){let t=this.request;t&&(this.release(),t.reject(e===void 0?it(`Terminal changed during text capture`):e))}release(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.request?.signal?.removeEventListener(`abort`,this.request.abort),this.request?.scan?.return(``),this.request=null}},Y=new WeakMap,ot=class{constructor(e){this.element=e,this.text=null,this.scan=null,this.timer=null,this.resolve=null,this.rectangle=null,this.decorated=new Set,this.onPointerDown=e=>{e.button===2&&this.element.contains(e.target)||this.clear()},this.onFocus=e=>{this.element.contains(e.target)||this.clear()},this.onSelectionChange=()=>{if(!this.active)return;let e=this.element.ownerDocument;x(e);let t=e.activeElement;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`)){let e=t;if(e.selectionStart!==e.selectionEnd){this.clear();return}}b(e)&&this.clear()},this.status=e.ownerDocument.createElement(`div`),this.status.className=`term-selection-status`,this.status.setAttribute(`role`,`status`),e.appendChild(this.status);let t=e.ownerDocument;t.addEventListener(`pointerdown`,this.onPointerDown,!0),t.addEventListener(`focusin`,this.onFocus),t.addEventListener(`selectionchange`,this.onSelectionChange)}get pending(){return this.resolve!==null}get active(){return this.pending||this.text!==null}get statusHeight(){return this.status.offsetHeight}getText(){return this.onSelectionChange(),this.text}select(){return this.claim(),this.status.textContent=`Selecting terminal text…`,new Promise(e=>{this.resolve=e})}selectRectangle(e){this.claim(),this.rectangle=e,this.text=e.text}paintRectangle(e,t){if(this.clearDecorations(),!this.rectangle||t<=0)return;let n=this.rectangle.rows[0].row;for(let{row:r,element:i}of e){let e=this.rectangle.rows[r-n];e&&(i.classList.add(`term-rectangle-row`),i.style.setProperty(`--term-selection-left`,`${e.left*t}px`),i.style.setProperty(`--term-selection-width`,`${(e.right-e.left)*t}px`),this.decorated.add(i))}}clearDecorations(){for(let e of this.decorated)e.classList.remove(`term-rectangle-row`),e.style.removeProperty(`--term-selection-left`),e.style.removeProperty(`--term-selection-width`);this.decorated.clear()}claim(){let e=this.element.ownerDocument;if(x(e),Y.get(e)?.clear(),this.clear(),Y.set(e,this),b(e)){let t=e.getSelection();t&&!t.isCollapsed&&(x(e),t.removeAllRanges())}}resume(e){if(!this.pending||this.scan)return;let t=this.scan=rt(e),n=()=>{this.timer=null;let e=performance.now()+4;try{for(let n=0;n<32;n++){let n=t.next();if(n.done){this.scan=null,this.text=n.value,this.element.classList.add(`term-select-all`),this.status.textContent=``;let e=this.resolve;this.resolve=null,e?.(!0);return}if(performance.now()>=e)break}this.timer=setTimeout(n,0)}catch{this.clear(),this.status.textContent=`Unable to select all text. Select a smaller range to copy.`}};this.timer=setTimeout(n,0)}clear(e=``){if(!this.active&&!this.status.textContent&&!e)return;this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.scan?.return(``),this.scan=null,this.text=null,this.rectangle=null,this.clearDecorations(),this.element.classList.remove(`term-select-all`),this.status.textContent=e,Y.get(this.element.ownerDocument)===this&&Y.delete(this.element.ownerDocument);let t=this.resolve;this.resolve=null,t?.(!1)}invalidate(){this.active&&this.clear(this.pending?`Terminal changed. Select all again to copy.`:``)}destroy(){this.clear();let e=this.element.ownerDocument;e.removeEventListener(`pointerdown`,this.onPointerDown,!0),e.removeEventListener(`focusin`,this.onFocus),e.removeEventListener(`selectionchange`,this.onSelectionChange),this.status.remove()}},st=class{constructor(e,t){this.element=e,this.callbacks=t,this.anchor=null,this.suppressClick=!1,this.owned=!1,this.lastEvent=null,this.frame=null,this.down=e=>{if(this.cancel(),this.owned=!1,this.suppressClick=!1,e.defaultPrevented||e.button!==0||!e.altKey||e.ctrlKey||e.metaKey)return;let t=this.callbacks.start(e);t&&this.callbacks.select(t,t)&&(this.anchor=t,this.owned=!0,e.preventDefault(),e.stopImmediatePropagation())},this.move=e=>{this.owned&&(e.buttons&1?(e.preventDefault(),e.stopImmediatePropagation(),this.update(e),this.lastEvent=e,this.scheduleScroll()):this.blur())},this.up=e=>{this.owned&&e.button===0&&(e.preventDefault(),e.stopImmediatePropagation(),this.update(e),this.cancel(),this.owned=!1,this.suppressClick=!0)},this.click=e=>{this.suppressClick&&e.detail!==0&&(this.suppressClick=!1,e.preventDefault(),e.stopImmediatePropagation())},this.key=e=>{this.anchor&&e.key===`Escape`&&(e.preventDefault(),e.stopImmediatePropagation(),this.cancel(),this.callbacks.clear())},this.cancel=()=>{this.anchor=null,this.lastEvent=null,this.frame!==null&&cancelAnimationFrame(this.frame),this.frame=null},this.blur=()=>{this.cancel(),this.owned=!1},this.focus=e=>{this.element.contains(e.target)||this.cancel()},e.addEventListener(`mousedown`,this.down,!0),e.addEventListener(`click`,this.click,!0);let n=e.ownerDocument;n.addEventListener(`mousemove`,this.move,!0),n.addEventListener(`mouseup`,this.up,!0),n.addEventListener(`keydown`,this.key,!0),n.addEventListener(`focusin`,this.focus),n.defaultView?.addEventListener(`blur`,this.blur)}update(e){let t=this.callbacks.position(e);!this.anchor||t&&this.callbacks.select(this.anchor,t)||this.callbacks.clear()}scheduleScroll(){this.frame===null&&this.anchor&&this.lastEvent&&(this.frame=requestAnimationFrame(()=>{if(this.frame=null,!this.anchor||!this.lastEvent)return;let e=this.element.getBoundingClientRect(),t=this.lastEvent.clientY,n=t<e.top?Math.max(-24,t-e.top):t>e.bottom?Math.min(24,t-e.bottom):0,r=this.element.scrollTop;this.element.scrollTop+=n,this.update(this.lastEvent),this.element.scrollTop!==r&&this.scheduleScroll()}))}destroy(){this.cancel(),this.element.removeEventListener(`mousedown`,this.down,!0),this.element.removeEventListener(`click`,this.click,!0);let e=this.element.ownerDocument;e.removeEventListener(`mousemove`,this.move,!0),e.removeEventListener(`mouseup`,this.up,!0),e.removeEventListener(`keydown`,this.key,!0),e.removeEventListener(`focusin`,this.focus),e.defaultView?.removeEventListener(`blur`,this.blur)}},ct=500,lt=32768,ut=65536,dt=20,ft=4e3,pt=`Output announcements paused because there is too much output. Type in the terminal or turn announcements off and on to resume.`,mt=class{constructor(e,t,n){this.host=e,this.getCore=t,this.ready=n,this.live=null,this.timer=null,this.previous=null,this.lines=0,this.characters=0,this.paused=!1,this.reset=()=>{this.invalidate(),this.lines=0,this.characters=0,this.paused=!1;let e=this.getCore();e&&this.active()&&(this.previous=this.snapshot(e),this.previous||this.limit())},e.addEventListener(`focusin`,this.reset),e.addEventListener(`focusout`,this.reset),e.ownerDocument.addEventListener(`visibilitychange`,this.reset),e.ownerDocument.defaultView?.addEventListener(`blur`,this.reset),e.ownerDocument.defaultView?.addEventListener(`focus`,this.reset)}setEnabled(e){e!==!!this.live&&(e?(this.live=this.host.ownerDocument.createElement(`div`),this.live.className=`term-announcements`,this.live.setAttribute(`role`,`log`),this.live.setAttribute(`aria-label`,`Terminal output`),this.live.setAttribute(`aria-live`,`polite`),this.live.setAttribute(`aria-relevant`,`additions`),this.live.setAttribute(`aria-atomic`,`false`),this.host.append(this.live)):(this.live?.remove(),this.live=null),this.reset())}active(){return!!this.live&&this.host.classList.contains(`focused`)&&this.host.isConnected&&this.host.ownerDocument.visibilityState!==`hidden`&&this.host.ownerDocument.hasFocus()}input(){this.paused?this.reset():(this.lines=0,this.characters=0)}invalidate(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.previous=null,this.live?.replaceChildren()}rendered(){if(!this.active()){this.invalidate();return}if(this.paused||this.timer!==null)return;let e=this.getCore();e&&(this.previous?this.timer=setTimeout(()=>{if(this.timer=null,!this.active()){this.invalidate();return}if(!this.ready())return;let e=this.getCore();e&&this.announce(e)},ct):(this.previous=this.snapshot(e),this.previous||this.limit()))}snapshot(e,t){let n=e.getCols(),r=e.getRows(),i=e.getScrollbackCount(),a=e.getScrollbackDiscardedCount?.()??0,o=i+a,s=t??o;if(s<a||(o+r-s)*n>lt)return null;let c=[],l=0;for(let t=s;t<o+r;t++){let r=o-t-1,i=t<o?e.getScrollbackLineLen(r):n;if(i>n)return null;let a=``;for(let n=0;n<i;n++){let i=t<o?e.getScrollbackCell(r,n):e.getCell(t-o,n);if(i.width===0||i.spacerHead)continue;let s=i.chars??String.fromCodePoint(i.char||32);if(l+=s.length,l>ut)return null;a+=s}c.push(a.replace(/ +$/,``))}return{base:s,cols:n,rows:r,alternate:e.usingAltScreen(),lines:c}}announce(e){let t=this.previous;if(!t)return;let n=e.getScrollbackCount()+(e.getScrollbackDiscardedCount?.()??0);if(t.cols!==e.getCols()||t.rows!==e.getRows()||t.alternate!==e.usingAltScreen()||n<t.base){this.previous=this.snapshot(e);return}let r=this.snapshot(e,t.base);if(!r){this.limit();return}let i=r.lines.filter((e,n)=>e.trim()&&e!==t.lines[n]);if(this.previous={...r,base:n,lines:r.lines.slice(n-r.base)},!i.length)return;let a=i.join(`
|
|
5
|
+
`);this.lines+i.length>dt||this.characters+a.length>ft?this.limit():(this.lines+=i.length,this.characters+=a.length,this.publish(a))}publish(e){if(!this.live)return;let t=this.host.ownerDocument.createElement(`div`);t.textContent=e,this.live.replaceChildren(t)}limit(){this.paused=!0,this.previous=null,this.publish(pt)}destroy(){this.setEnabled(!1),this.host.removeEventListener(`focusin`,this.reset),this.host.removeEventListener(`focusout`,this.reset),this.host.ownerDocument.removeEventListener(`visibilitychange`,this.reset),this.host.ownerDocument.defaultView?.removeEventListener(`blur`,this.reset),this.host.ownerDocument.defaultView?.removeEventListener(`focus`,this.reset)}},ht={1:`bold`,2:`dim`,4:`italic`,8:`underline`,16:`blink`,32:`reverse`,64:`invisible`,128:`strikethrough`};function gt(e){let t=[];for(let[n,r]of Object.entries(ht))e&Number(n)&&t.push(r);return t}var X=27;function _t(e){let t=[],n=Date.now(),r=0,i=0,a=()=>{if(r>i){let a=e.slice(i,r);a.length>0&&!/^[\x00-\x1f]+$/.test(a)&&t.push({ts:n,type:`text`,raw:a.slice(0,60)})}};for(;r<e.length;){if(e.charCodeAt(r)!==X){r++;continue}a();let o=r;if(r++,r>=e.length)break;let s=e[r];if(s===`[`){r++;let i=``;r<e.length&&(e[r]===`?`||e[r]===`>`||e[r]===`!`)&&(i=e[r],r++);let a=``;for(;r<e.length&&(e.charCodeAt(r)>=48&&e.charCodeAt(r)<=59||e[r]===`:`);)a+=e[r],r++;for(;r<e.length&&e.charCodeAt(r)>=32&&e.charCodeAt(r)<=47;)r++;let s=``;r<e.length&&e.charCodeAt(r)>=64&&e.charCodeAt(r)<=126&&(s=e[r],r++);let c=e.slice(o,r),l=a?a.split(/[;:]/).map(Number).filter(e=>!isNaN(e)):[],u=s===`m`?`sgr`:`csi`;t.push({ts:n,type:u,raw:c,params:l.length>0?l:void 0,private:i||void 0,final:s})}else if(s===`]`){for(r++;r<e.length&&e.charCodeAt(r)!==7&&!(e.charCodeAt(r)===X&&r+1<e.length&&e[r+1]===`\\`);)r++;r<e.length&&(e.charCodeAt(r)===7?r++:e.charCodeAt(r)===X&&(r+=2));let i=e.slice(o,r);t.push({ts:n,type:`osc`,raw:i.slice(0,80)})}else s>=` `&&s<=`~`?(r++,t.push({ts:n,type:`esc`,raw:e.slice(o,r),final:s})):r++;i=r}return a(),t}var vt=500,yt=class{constructor(){this._traces=[],this._bridge=null,this._perf={frameCount:0,totalRenderMs:0,avgRenderMs:0,maxRenderMs:0,lastDirtyRows:0}}get traces(){return this._traces}get perf(){return this._perf}setBridge(e){this._bridge=e}traceWrite(e){let t=_t(typeof e==`string`?e:new TextDecoder().decode(e));for(let e of t)this._traces.push(e);this._traces.length>vt&&(this._traces=this._traces.slice(-500))}recordRender(e,t){this._perf.frameCount++,this._perf.totalRenderMs+=e,this._perf.avgRenderMs=this._perf.totalRenderMs/this._perf.frameCount,e>this._perf.maxRenderMs&&(this._perf.maxRenderMs=e),this._perf.lastDirtyRows=t}resetPerf(){this._perf={frameCount:0,totalRenderMs:0,avgRenderMs:0,maxRenderMs:0,lastDirtyRows:0}}cell(e,t){if(!this._bridge)return null;let n=this._bridge.getCell(e,t);return{...n,charStr:n.chars??(n.char>=32?String.fromCodePoint(n.char):``),flagNames:gt(n.flags)}}row(e){if(!this._bridge)return null;let t=this._bridge.getCols(),n=[];for(let r=0;r<t;r++)n.push(this.cell(e,r));return n}grid(){if(!this._bridge)return null;let e=this._bridge.getCursor();return{rows:this._bridge.getRows(),cols:this._bridge.getCols(),cursor:e,altScreen:this._bridge.usingAltScreen(),scrollbackCount:this._bridge.getScrollbackCount()}}unhandled(){return this._bridge?this._bridge.getUnhandledSequences():[]}dump(e=50){let t=this._traces.slice(-e);console.group(`%cwterm debug — last ${t.length} traces`,`color: #569cd6; font-weight: bold`);for(let e of t){let t=e.type===`sgr`?`%cSGR`:e.type===`csi`?`%cCSI`:e.type===`osc`?`%cOSC`:e.type===`esc`?`%cESC`:`%cTXT`,n=e.type===`sgr`?`background:#2d5a27;color:#fff;padding:1px 4px;border-radius:2px`:e.type===`csi`?`background:#1e4a7a;color:#fff;padding:1px 4px;border-radius:2px`:`background:#555;color:#fff;padding:1px 4px;border-radius:2px`,r=[e.private?`private=${e.private}`:``,e.params?`params=[${e.params}]`:``,e.final?`final=${e.final}`:``].filter(Boolean).join(` `);console.log(`${t} ${e.raw.slice(0,40)}`,n,r?` ${r}`:``)}console.groupEnd()}dumpUnhandled(){let e=this.unhandled();if(e.length===0)console.log(`%cwterm debug — no unhandled sequences`,`color: #6a9955`);else{console.group(`%cwterm debug — ${e.length} unhandled sequences`,`color: #d7ba7d; font-weight: bold`);for(let t of e)console.log(` final=${t.final} private=${t.private||`-`} params=[${t.params.slice(0,t.paramCount)}]`);console.groupEnd()}}};function bt(e,t){if(t)return e;if(e.length<=1)return e.toLowerCase();let n=``;for(let t of e)n+=t.toLowerCase();return n}function*xt(e,t,n){let r=bt(t,n);if(!r)return;let i=new Uint32Array(r.length);for(let e=1,t=0;e<r.length;e++){for(;t>0&&r[e]!==r[t];)t=i[t-1];r[e]===r[t]&&t++,i[e]=t}let a=Array(r.length),o=e.getScrollbackCount(),s=0,c=0,l=0,u=!1,d;for(let t=0;t<o+e.getRows();t++){let f=o-1-t,p=t<o?e.getScrollbackRowMetadata?.(f):e.getRowMetadata?.(t-o);u&&p?.continuesPrevious||(s=0),u=p?.wrapsToNext??!1;let m=t<o?e.getScrollbackLineLen(f):e.getCols();for(let u=0;u<m;u++){++l>=256&&(l=0,yield null);let p=t<o?e.getScrollbackCell(f,u):e.getCell(t-o,u);if(p.width===0||p.spacerHead)continue;let h=bt(p.chars??String.fromCodePoint(p.char||32),n);if(s===0&&h.length===1&&h!==r[0])continue;let g={row:t,col:u,endCol:Math.min(m,u+(p.width??1))};for(let e=0;e<h.length;e++){for(++l>=256&&(l=0,yield null),a[c++%r.length]=g;s>0&&h[e]!==r[s];)s=i[s-1];if(h[e]===r[s]&&s++,s===r.length){let e={start:a[(c-r.length)%r.length],end:g};d&&d.start.row===e.start.row&&d.start.col===e.start.col&&d.end.row===e.end.row&&d.end.endCol===e.end.endCol||(yield e,d=e),s=i[s-1]}}}++l>=256&&(l=0,yield null)}}var St=class{constructor(e){this.changed=e,this.matches=[],this.state={query:``,caseSensitive:!1,count:0,activeIndex:-1,searching:!1,limited:!1},this.timer=null,this.channel=null,this.scan=null,this.pending=!1,this.revealFirst=!1}snapshot(){return{...this.state}}search(e,t){if(e.length>1024)throw RangeError(`Search query exceeds 1,024 UTF-16 code units`);this.state.query=e,this.state.caseSensitive=t.caseSensitive??!1,this.revealFirst=!0,this.invalidate()}invalidate(){this.cancel(),this.matches=[],this.state.count=0,this.state.activeIndex=-1,this.state.limited=!1,this.pending=this.state.searching=this.state.query.length>0,this.changed(!1)}resume(e){if(!this.pending)return;this.pending=!1;let t=this.scan=xt(e,this.state.query,this.state.caseSensitive),n=()=>{if(this.scan!==t)return;this.timer=null;let e=performance.now()+4,r=!1;do{let e=t.next();if(e.done){r=!0;break}if(e.value){if(this.matches.length===1e4){this.state.limited=!0,r=!0;break}this.matches.push(e.value)}}while(performance.now()<e);this.state.count=this.matches.length;let i=this.revealFirst&&this.matches.length>0;this.matches.length&&this.state.activeIndex===-1&&(this.state.activeIndex=0),i&&(this.revealFirst=!1),this.state.searching=!r,r&&(t.return(void 0),this.scan=null,this.clearTask()),this.changed(i),this.scan===t&&this.schedule(n)};this.schedule(n)}schedule(e){if(typeof MessageChannel>`u`)this.timer=setTimeout(e,0);else{let t=this.channel??=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(null)}}clearTask(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.channel&&=(this.channel.port1.onmessage=null,this.channel.port1.close(),this.channel.port2.close(),null)}navigate(e){return this.matches.length?(this.state.activeIndex=(this.state.activeIndex+e+this.matches.length)%this.matches.length,this.revealFirst=!1,this.changed(!0),!0):!1}cancel(){this.clearTask(),this.scan?.return(void 0),this.scan=null,this.pending=!1,this.matches=[],this.state.count=0,this.state.activeIndex=-1,this.state.searching=!1,this.state.limited=!1}},Ct=1e3,wt=1,Z=new Set,Q=null,$=[`--term-fg`,`--term-bg`,`--term-cursor`,...Array.from({length:16},(e,t)=>`--term-color-${t}`)];function Tt(e){if(typeof e==`string`)return e.includes(`\x1B]10;`)||e.includes(`\x1B]11;`);for(let t=e.indexOf(27);t>=0;t=e.indexOf(27,t+1))if(e[t+1]===93&&e[t+2]===49&&(e[t+3]===48||e[t+3]===49)&&e[t+4]===59)return!0;return!1}function Et(e){let t=e.ownerDocument.createElement(`span`);t.style.display=`none`,e.appendChild(t);try{let e=[];for(let n of $){t.style.color=`var(${n})`;let r=Dt(getComputedStyle(t).color);if(r===null)return null;e.push(r)}return{foreground:e[0],background:e[1],cursor:e[2],palette:e.slice(3)}}finally{t.remove()}}function Dt(e){if(typeof e!=`string`)return null;let t=e.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/);if(t)return Math.round(Number(t[1]))<<16|Math.round(Number(t[2]))<<8|Math.round(Number(t[3]));try{let t=document.createElement(`canvas`).getContext(`2d`,{willReadFrequently:!0});if(!t)return null;t.fillStyle=e,t.fillRect(0,0,1,1);let[n,r,i]=t.getImageData(0,0,1,1).data;return n<<16|r<<8|i}catch{return null}}var Ot=class e{constructor(e,t={}){this.bridge=null,this.debug=null,this._themeColors=null,this._cssThemeKey=null,this.renderer=null,this.input=null,this._synchronizedOutputTimer=null,this._synchronizedOutputState=`idle`,this._synchronizedOutputGeneration=0,this._rendererNeedsSetup=!1,this.resizeObserver=null,this._destroyed=!1,this._shouldScrollToBottom=!1,this._pinnedToBottom=!0,this._scrollbackDiscardedCount=0,this._programmaticScrollTop=null,this._pendingResizeScrollTop=null,this._rowHeight=0,this._charWidth=0,this._windowSizeQueryState=0,this._textCapture=new at,this._searchReveal=!1,this._onCoreUpdate=()=>{if(!this.bridge||this._destroyed)return;this._textCapture.cancel(),this._rectangleDrag.cancel(),this.renderer?.beforeMutation(this.bridge),this._historySelection.invalidate();let e=this._deliverCoreEffects(),t=this.bridge.synchronizedOutput?.()??!1,n=this.bridge.synchronizedOutputGeneration?.()??0;if(this._updateSynchronizedOutput(t,n),this._invalidateSearch(),this._synchronizedOutputState!==`held`&&(this._setupRendererIfNeeded(),this._scheduleRender()),e.hasError){let t=e.error;queueMicrotask(()=>{throw t})}},this._lastContainerRect=null,this._keyboardSpacer=null,this._keyboardInset=0,this._visualViewport=null,this._visualViewportFrame=0,this._onVisualViewportChange=()=>{this._visualViewportFrame||this._destroyed||(this._visualViewportFrame=requestAnimationFrame(()=>{this._visualViewportFrame=0,this._fitAutoResize()}))},this.element=e,this._coreOption=t.core,this._initialColsExplicit=t.cols!==void 0,this._initialRowsExplicit=t.rows!==void 0,this.wasmUrl=t.wasmUrl,this.maxImageWidth=t.maxImageWidth,this.maxImageHeight=t.maxImageHeight,this.cols=t.cols||80,this.rows=t.rows||24,this.autoResize=t.autoResize!==!1,this._debugEnabled=t.debug??!1,this._renderingPaused=t.renderingPaused??!1,this.onData=t.onData||null,this.onBinary=t.onBinary||null,this.onTitle=t.onTitle||null,this.onWorkingDirectory=t.onWorkingDirectory||null,this.onBell=t.onBell||null,this.onShellIntegration=t.onShellIntegration||null,this.onClipboardWrite=t.onClipboardWrite||null,this.onResize=t.onResize||null,this.onSearchChange=t.onSearchChange||null,this._search=new St(e=>{if(this._searchReveal||=e,e){let e=this._search.matches[this.getSearchState().activeIndex];e&&(this._shouldScrollToBottom=!1,this._pendingResizeScrollTop=null,this._setScrollTop((e.start.row+.5)*this._rowHeight-this.element.clientHeight/2))}this._synchronizedOutputState!==`held`&&this._scheduleRender(),this.onSearchChange?.(this.getSearchState())}),this._container=document.createElement(`div`),this._container.className=`term-grid`,this.element.appendChild(this._container),this.element.classList.add(`wterm`),this._historySelection=new ot(this.element),this._rectangleDrag=new st(this.element,{start:e=>{if(!(e.target instanceof Element)||!this.bridge||!this._canRender())return null;let t=this.renderer?.positionAt(e.target,e.clientX,this._charWidth);return!t||!e.shiftKey&&this.bridge.mouseTracking?.()&&t.row>=this.bridge.getScrollbackCount()?null:t},position:e=>{let t=this.element.getBoundingClientRect();return this.renderer?.dragPositionAt(e.clientX,Math.max(t.top+1,Math.min(t.bottom-1,e.clientY)),this._charWidth)??null},select:(e,t)=>this.selectRectangle(e,t),clear:()=>this._historySelection.clear()}),this._outputAnnouncements=new mt(this.element,()=>this.bridge,()=>this._canRender()&&!Z.has(this)&&this._synchronizedOutputState!==`held`),this._outputAnnouncements.setEnabled(t.announceOutput??!1),this._onVisibilityChange=()=>{this._canRender()?this._scheduleRender():(this._rectangleDrag.cancel(),this._cancelScheduledRender(),this._outputAnnouncements.invalidate())},this.element.ownerDocument.addEventListener(`visibilitychange`,this._onVisibilityChange),this.element.classList.toggle(`cursor-blink`,t.cursorBlink===!0),this.element.classList.toggle(`cursor-steady`,t.cursorBlink===!1),this._onClickFocus=e=>{if(e.defaultPrevented||this._historySelection.active)return;let t=e.target;if(t instanceof Element&&t.closest(`.term-link`)){if(H(e,this.element.ownerDocument.defaultView?.navigator??navigator)||e.detail===0)return;e.preventDefault()}let n=window.getSelection();(!n||n.isCollapsed)&&this.input?.focus()},this._onMouseSelect=e=>{if(e.defaultPrevented||e.button!==0||e.detail!==2&&e.detail!==3||e.altKey||e.ctrlKey||e.metaKey||!(e.target instanceof Element))return;let t=this.renderer?.positionAt(e.target,e.clientX,this._charWidth);t&&this.bridge&&(!e.shiftKey&&this.bridge.mouseTracking?.()&&t.row>=this.bridge.getScrollbackCount()||(e.detail===2?this.selectWord(t):this.selectLine(t.row))&&e.preventDefault())},this.element.addEventListener(`click`,this._onMouseSelect),this.element.addEventListener(`click`,this._onClickFocus),this._onModifierChange=e=>{this.element.classList.toggle(`link-modifier-active`,H(e,this.element.ownerDocument.defaultView?.navigator??navigator))},this._onWindowBlur=()=>{this.element.classList.remove(`link-modifier-active`)},this.element.ownerDocument.addEventListener(`keydown`,this._onModifierChange),this.element.ownerDocument.addEventListener(`keyup`,this._onModifierChange),this.element.ownerDocument.defaultView?.addEventListener(`blur`,this._onWindowBlur),this._onBeforePrint=()=>this._setPrintMode(!0),this._onAfterPrint=()=>this._setPrintMode(!1),this.element.ownerDocument.defaultView?.addEventListener(`beforeprint`,this._onBeforePrint),this.element.ownerDocument.defaultView?.addEventListener(`afterprint`,this._onAfterPrint),this._onScroll=()=>{if(this._pendingResizeScrollTop!==null)return;let e=this._isScrolledToBottom();this._shouldScrollToBottom&&e||this._programmaticScrollTop!==null&&Math.abs(this.element.scrollTop-this._programmaticScrollTop)<=wt?this._programmaticScrollTop=null:(this._programmaticScrollTop=null,this._shouldScrollToBottom=!1,this._scheduleRender())},this.element.addEventListener(`scroll`,this._onScroll,{passive:!0}),this._onCopy=e=>{if(e.defaultPrevented||!e.clipboardData)return;let t=e.target;if(t instanceof Element&&!this.element.contains(t)&&(t.closest(`input, textarea`)||t.isContentEditable))return;let n=this.getSelectionText();this._historySelection.pending?e.preventDefault():n!==null&&(e.clipboardData.setData(`text/plain`,n),e.preventDefault())},this.element.ownerDocument.addEventListener(`copy`,this._onCopy)}async init(){try{if(this.bridge=this._coreOption?this._coreOption:await l.load(this.wasmUrl),this._destroyed)return this;this.bridge.setUpdateListener?.(this._onCoreUpdate);let e=this.cols,t=this.rows;if(this._setRowHeight(),this.autoResize){let e=this._measureGridSize();e&&(this._initialColsExplicit||(this.cols=e.cols),this._initialRowsExplicit||(this.rows=e.rows))}this.bridge.init(this.cols,this.rows),this._themeColors?this.bridge.setThemeColors?.(this._themeColors):this._syncCssThemeColors(),this.cols=this.bridge.getCols(),this.rows=this.bridge.getRows(),this._debugEnabled&&(this.debug=new yt,this.debug.setBridge(this.bridge),globalThis.__wterm=this),this._measureCharSize(),this.renderer=new Pe(this._container,{colorHost:this.element,maxImageWidth:this.maxImageWidth,maxImageHeight:this.maxImageHeight}),this.renderer.setup(this.cols,this.rows),this.input=new tt(this.element,(e,t=!1)=>{t||(this._outputAnnouncements.input(),this._scrollToBottom()),this.onData?this.onData(e):this.write(e)},()=>this.bridge,()=>this._charWidth>0&&this._rowHeight>0?{charWidth:this._charWidth,rowHeight:this._rowHeight}:null,()=>{this._rectangleDrag.cancel(),this._historySelection.clear(),this._scrollToBottom()},e=>{this._outputAnnouncements.input(),this._rectangleDrag.cancel(),this._historySelection.clear(),this._scrollToBottom(),this.onBinary?this.onBinary(e):this.onData?e.every(e=>e<128)&&this.onData(String.fromCharCode(...e)):this.write(e)},{selectAll:()=>{this.selectAll()},hasSelection:()=>this._historySelection.active,clearSelection:()=>{this._rectangleDrag.cancel(),this._historySelection.clear()}}),this._setupResizeObserver(),this.autoResize||this._lockHeight(),this.input.focus(),this._initialRender(),(this.cols!==e||this.rows!==t)&&this.onResize?.(this.cols,this.rows)}catch(e){throw this.destroy(),Error(`wterm: failed to initialize: ${e instanceof Error?e.message:e}`)}return this}_isScrolledToBottom(){let e=this.element;return this._pinnedToBottom=e.scrollHeight-e.scrollTop-e.clientHeight<5,this._pinnedToBottom}_scrollToBottom(){this._setScrollTop(this.element.scrollHeight)}_setScrollTop(e,t){if(!t){let t=this.element.scrollTop;this.element.scrollTop=e;let n=this.element.scrollTop;this._isScrolledToBottom(),n!==t&&(this._programmaticScrollTop=n);return}let n=t.maxScrollTop,r=Math.max(0,Math.min(e,n));this._pinnedToBottom=n-r<5,(r!==t.viewportScrollTop||t.restoreScroll)&&(this._programmaticScrollTop=r),this.element.scrollTop=r}setThemeColors(e){if(e===null){if(this._destroyed)return;this._themeColors=null;for(let e of $)this.element.style.removeProperty(e);this._cssThemeKey=null,this._syncCssThemeColors(),this.renderer?.invalidateColors(),this._scheduleRender();return}let t=[e.foreground,e.background,e.cursor,...e.palette];if(e.palette.length!==16||t.some(e=>!Number.isInteger(e)||e<0||e>16777215))throw RangeError(`Theme colors must be 24-bit RGB values with exactly 16 palette entries`);if(this._destroyed)return;let n={...e,palette:[...e.palette]};this.bridge?.setThemeColors?.(n),this._themeColors=n,t.forEach((e,t)=>this.element.style.setProperty($[t],`#${e.toString(16).padStart(6,`0`)}`)),this.renderer?.invalidateColors(),this._scheduleRender()}write(e){if(!this.bridge||this._destroyed)return;x(this.element.ownerDocument),this._textCapture.cancel(),this._rectangleDrag.cancel(),this._historySelection.invalidate(),this.renderer?.beforeMutation(this.bridge),this.debug&&this.debug.traceWrite(e),this._shouldScrollToBottom=this._pinnedToBottom,Tt(e)&&this._syncCssThemeColors();let t=this._collectWindowSizeQueries(e),n,r=!1,i=e=>{r||(r=!0,n=e)},a=()=>{let e=this._deliverCoreEffects();e.hasError&&i(e.error)};typeof e==`string`?this.bridge.writeString(e,a):this.bridge.writeRaw(e,a);let o=this.bridge.synchronizedOutput?.()??!1,s=this.bridge.synchronizedOutputGeneration?.()??0;this._updateSynchronizedOutput(o,s),this._invalidateSearch(),this._synchronizedOutputState!==`held`&&(this._setupRendererIfNeeded(),this._scheduleRender()),a();for(let e of t)try{this.onData?.(this._windowSizeResponse(e))}catch(e){i(e)}if(r)throw n}_syncCssThemeColors(){if(this._themeColors||!this.bridge?.setThemeColors||this._destroyed)return;let e;try{e=Et(this.element)}catch{return}if(!e)return;let t=[e.foreground,e.background,e.cursor,...e.palette].join();t!==this._cssThemeKey&&(this._cssThemeKey=t,this.bridge.setThemeColors(e))}_deliverCoreEffects(){let e=!1,t,n=n=>{e||(e=!0,t=n)},r=this._drainResponses();r.hasError&&n(r.error);let i=this.bridge?.getBellCount?.()??0;if(i>0)try{this.onBell?.(i)}catch(e){n(e)}try{this._deliverTitle()}catch(e){n(e)}try{let e=this.bridge?.getClipboardWrite?.()??null;e!==null&&!this._destroyed&&this.onClipboardWrite?.(e)}catch(e){n(e)}try{let e=this.bridge?.getShellIntegrationState?.()??null;e!==null&&!this._destroyed&&this.onShellIntegration?.(e)}catch(e){n(e)}try{let e=this.bridge?.getWorkingDirectory?.()??null;e!==null&&!this._destroyed&&this.onWorkingDirectory?.(e)}catch(e){n(e)}return{hasError:e,error:t}}fit(){if(!this.bridge||this._destroyed)return;let e=this._measureGridSize();e&&(e.cols!==this.cols||e.rows!==this.rows)&&this.resize(e.cols,e.rows)}_measureGridSize(){let e=this._measureCharSize();if(!e)return null;let t=getComputedStyle(this.element),n=this.element.getBoundingClientRect(),r=e=>parseFloat(e)||0,i=r(t.borderLeftWidth)+r(t.borderRightWidth),a=r(t.borderTopWidth)+r(t.borderBottomWidth),o=Math.max(0,this.element.offsetWidth-this.element.clientWidth-i),s=Math.max(0,this.element.offsetHeight-this.element.clientHeight-a),c=n.width-r(t.paddingLeft)-r(t.paddingRight)-i-o,l=n.height-r(t.paddingTop)-r(t.paddingBottom)-a-s;return c<=0||l<=0?null:{cols:Math.max(1,Math.floor(c/e.charWidth)),rows:Math.max(1,Math.floor(l/e.rowHeight))}}resize(e,t){if(!this.bridge||this._destroyed)return;x(this.element.ownerDocument),this._textCapture.cancel(),this._rectangleDrag.cancel(),this._historySelection.invalidate(),this.renderer?.beforeMutation(this.bridge),this._shouldScrollToBottom=this._pendingResizeScrollTop===null&&this._isScrolledToBottom(),this.bridge.resize(e,t),this._outputAnnouncements.invalidate(),this.cols=this.bridge.getCols(),this.rows=this.bridge.getRows();let n=this.bridge.synchronizedOutput?.()??!1,r=this.bridge.synchronizedOutputGeneration?.()??0;this._updateSynchronizedOutput(n,r)?this._rendererNeedsSetup=!0:(this._setupRenderer(),this._scheduleRender()),this._invalidateSearch(),this.onResize&&this.onResize(this.cols,this.rows)}search(e,t={}){this._destroyed||(this._search.search(e,t),this._paintSearch())}findNext(){return!this._destroyed&&this._search.navigate(1)}findPrevious(){return!this._destroyed&&this._search.navigate(-1)}clearSearch(){this.search(``)}getSearchState(){return this._search.snapshot()}scrollToPrompt(e){if(!this._canRender()||!this.bridge?.findPrompt||!this.renderer||this._synchronizedOutputState===`held`||this.bridge.usingAltScreen()||e!==-1&&e!==1||(this._cancelScheduledRender(),this._doRender(),e===1&&this._isScrolledToBottom()))return!1;let t=this.element.getBoundingClientRect(),n=this.renderer.dragPositionAt(t.left,t.top+this.element.clientTop+1,this._charWidth);if(!n)return!1;let r=this.bridge.findPrompt(n.row,e);if(r===null||!Number.isInteger(r)||r<0||r>=this.bridge.getScrollbackCount()+this.rows||(e<0?r>=n.row:r<=n.row))return!1;let i=this.element.scrollTop;this._shouldScrollToBottom=!1,this._searchReveal=!1,this._pendingResizeScrollTop=r*this._rowHeight,this._doRender();let a=Array.from(this.renderer.searchRows()).find(({row:e})=>e===r);return a&&this._setScrollTop(this.element.scrollTop+a.element.getBoundingClientRect().top-t.top-this.element.clientTop),this._scheduleRender(),Math.abs(this.element.scrollTop-i)>wt}setOutputAnnouncements(e){this._destroyed||this._outputAnnouncements.setEnabled(e)}setRenderingPaused(e){this._destroyed||e===this._renderingPaused||(this._renderingPaused=e,this._onVisibilityChange())}_canRender(){return!this._destroyed&&!this._renderingPaused&&this.element.ownerDocument.visibilityState!==`hidden`}readText(e={}){if(this._destroyed||!this.renderer||!this.bridge)return Promise.reject(Error(`Terminal is not initialized`));let t=this._textCapture.read(e.signal);return this._scheduleRender(),t}getSelectionText(){return this._destroyed?null:this._historySelection.getText()??this.renderer?.getSelectionText()??null}selectAll(){if(this._destroyed||!this.renderer||!this.bridge)return Promise.resolve(!1);this._rectangleDrag.cancel();let e=this._historySelection.select();return this._scheduleRender(),e}selectWord(e){return this._selectUnit(e,`word`)}selectLine(e){return this._selectUnit({row:e,col:0},`line`)}selectRectangle(e,t){if(this._destroyed||!this.bridge||!this.renderer||!this._canRender())return!1;let n=this.renderer.rectangle(this.bridge,e,t,()=>{this.input?.focus()});return n?(this._historySelection.selectRectangle(n),this._historySelection.paintRectangle(this.renderer.searchRows(),this._charWidth),!0):!1}_selectUnit(e,t){return this._destroyed||!this.bridge||!this.renderer?!1:this.renderer.select(this.bridge,e,t,()=>{this._rectangleDrag.cancel(),this._historySelection.clear();let e=this.element.ownerDocument.activeElement;e instanceof HTMLElement&&this.element.contains(e)&&e.tagName===`TEXTAREA`&&e.blur()})}clearSelection(){this._rectangleDrag.cancel(),this._historySelection.clear();let e=this.element.ownerDocument.getSelection();if(e&&!e.isCollapsed){for(let t=0;t<e.rangeCount;t++){let n=e.getRangeAt(t);if(!this.element.contains(n.startContainer)||!this.element.contains(n.endContainer))return}x(this.element.ownerDocument),e.removeAllRanges()}}_invalidateSearch(){this.getSearchState().query&&(this._searchReveal=!1,this._search.invalidate(),this._paintSearch())}_paintSearch(){if(!this.renderer||!this.bridge||!this._canRender())return;let e=document.createDocumentFragment(),t=this._search.matches;if(!t.length){this.renderer.setSearchDecorations(e);return}let n=this.getSearchState().activeIndex,r=this.element.getBoundingClientRect();for(let{row:i,element:a}of this.renderer.searchRows()){let o=a.getBoundingClientRect();if(o.bottom<=r.top||o.top>=r.bottom)continue;let s=0,c=t.length;for(;s<c;){let e=s+c>>>1;t[e].end.row<i?s=e+1:c=e}let l=this.bridge.getScrollbackCount(),u=l-i-1,d=i<l?this.bridge.getScrollbackLineLen(u):this.cols;if(d<=0)continue;(i<l?this.bridge.getScrollbackCell(u,d-1):this.bridge.getCell(i-l,d-1)).spacerHead&&d--;let f=-1,p=-1,m=(t,n,r)=>{if(n<=t)return;let i=document.createElement(`div`);i.className=`term-search-match${r?` term-search-active`:``}`,i.style.cssText=`left:${t*this._charWidth}px;top:${a.offsetTop}px;width:${(n-t)*this._charWidth}px;height:${o.height}px`,e.appendChild(i)};for(let e=s;e<t.length&&t[e].start.row<=i;e++){let n=t[e],r=n.start.row===i?n.start.col:0,a=Math.min(d,n.end.row===i?n.end.endCol:d);f>=0&&r>p&&(m(f,p,!1),f=-1),f<0&&(f=r),p=Math.max(p,a)}f>=0&&m(f,p,!1);let h=t[n];h&&h.start.row<=i&&h.end.row>=i&&m(h.start.row===i?h.start.col:0,Math.min(d,h.end.row===i?h.end.endCol:d),!0)}this.renderer.setSearchDecorations(e)}focus(){this.input?this.input.focus():this.element.focus()}_scheduleRender(){if(this._canRender()&&this._synchronizedOutputState!==`held`&&!Z.has(this)&&(Z.add(this),Q===null)){let t=requestAnimationFrame(e._flushRenders);Z.size>0&&(Q=t)}}_cancelScheduledRender(){Z.delete(this),Z.size===0&&Q!==null&&(cancelAnimationFrame(Q),Q=null)}static _flushRenders(){Q=null;let e=new Map,t=Array.from(Z);for(let e of new Set(t.map(e=>e.element.ownerDocument)))x(e);for(let n of[`read`,`render`,`measure`,`scroll`,`finish`])for(let r of t)try{if(n===`read`){if(!Z.delete(r))continue;let t=r._readRender();t&&e.set(r,t);continue}let t=e.get(r);if(!t)continue;n===`render`?r._renderFrame(t):n===`measure`?r._measureRenderScroll(t):n===`scroll`?r._scrollRender(t):r._finishRender()}catch(t){e.delete(r),queueMicrotask(()=>{throw t})}}_updateSynchronizedOutput(e,t){return e?this._synchronizedOutputState===`held`&&t!==this._synchronizedOutputGeneration?(this._armSynchronizedOutputFallback(t),!0):(this._synchronizedOutputState===`passthrough`&&t!==this._synchronizedOutputGeneration&&(this._synchronizedOutputState=`idle`),this._synchronizedOutputState===`idle`?(this._synchronizedOutputState=`held`,this._cancelScheduledRender(),this._armSynchronizedOutputFallback(t),!0):this._synchronizedOutputState===`held`):(this._synchronizedOutputState===`held`&&this._cancelSynchronizedOutputFallback(),this._synchronizedOutputState=`idle`,!1)}_armSynchronizedOutputFallback(e){this._cancelSynchronizedOutputFallback(),this._synchronizedOutputGeneration=e,this._synchronizedOutputTimer=setTimeout(()=>{this._synchronizedOutputState===`held`&&this._synchronizedOutputGeneration===e&&(this._synchronizedOutputTimer=null,this._synchronizedOutputState=`passthrough`,this._setupRendererIfNeeded(),this._cancelScheduledRender(),this._doRender())},Ct)}_cancelSynchronizedOutputFallback(){this._synchronizedOutputTimer!=null&&(clearTimeout(this._synchronizedOutputTimer),this._synchronizedOutputTimer=null)}_setPrintMode(e){if(!this.renderer||this._destroyed)return;let t=e&&(!this._canRender()||this._synchronizedOutputState===`held`);this.element.classList.toggle(`term-print-canvas`,t),this.renderer.setCanvasSuspended(e&&!t),t||(e?this._doRender():this._scheduleRender())}_setupRendererIfNeeded(){this._rendererNeedsSetup&&=(this._setupRenderer(),!1)}_setupRenderer(){!this._shouldScrollToBottom&&this._pendingResizeScrollTop===null&&(this._pendingResizeScrollTop=this.element.scrollTop),this.renderer?.requestSetup()}_initialRender(){this._doRender()}_doRender(){this._cancelScheduledRender(),x(this.element.ownerDocument);let e=this._readRender();e&&(this._renderFrame(e),this._measureRenderScroll(e),this._scrollRender(e),this._finishRender())}_readRender(){if(!this._canRender()||!this.bridge||!this.renderer||this._synchronizedOutputState===`held`)return null;let e=0;if(this.debug)for(let t=0;t<this.rows;t++)this.bridge.isDirtyRow(t)&&e++;let t=this._rowHeight||17,n=this.element.scrollTop,r=this.element.clientHeight;this._pinnedToBottom=this.element.scrollHeight-n-r<5;let i=getComputedStyle(this.element),a=(parseFloat(i.paddingTop)||0)+(parseFloat(i.paddingBottom)||0),o=this.bridge.getScrollbackCount(),s=this.bridge.getScrollbackDiscardedCount?.(),c=s!==void 0&&s>=this._scrollbackDiscardedCount?s-this._scrollbackDiscardedCount:0;s!==void 0&&(this._scrollbackDiscardedCount=s);let l=this._pendingResizeScrollTop===null?n:this._pendingResizeScrollTop;return!this._shouldScrollToBottom&&c>0&&(l=Math.max(0,l-c*t)),{scrollTop:l,viewportScrollTop:n,clientHeight:r,maxScrollTop:Math.max(0,Math.round((o+this.rows)*t+a+this._keyboardInset+this._historySelection.statusHeight)-r),rowHeight:t,scrollbackCount:o,discardedCount:s,dirtyCount:e,followOutput:this._shouldScrollToBottom,restoreScroll:this._pendingResizeScrollTop!==null||c>0}}_renderFrame(e){if(!this.bridge||!this.renderer)return;let t=this.debug?performance.now():0;this.renderer.render(this.bridge,{scrollTop:e.followOutput?Math.max(0,(e.scrollbackCount+this.rows)*e.rowHeight-e.clientHeight):e.scrollTop,clientHeight:e.clientHeight,rowHeight:e.rowHeight,scrollbackDiscardedCount:e.discardedCount,charWidth:this._charWidth}),this.debug&&this.debug.recordRender(performance.now()-t,e.dirtyCount);let n=e.scrollbackCount>0||this.renderer.hasImageFlow;this.element.classList.toggle(`has-scrollback`,n)}_measureRenderScroll(e){this.renderer?.hasImageFlow&&(e.maxScrollTop=Math.max(0,this.element.scrollHeight-e.clientHeight))}_scrollRender(e){this._pendingResizeScrollTop=null,e.followOutput?this._setScrollTop(e.maxScrollTop,e):e.restoreScroll?this._setScrollTop(e.scrollTop,e):!e.scrollbackCount&&!this.renderer?.hasImageFlow&&this._setScrollTop(0,e)}_finishRender(){if(this.bridge&&this.renderer&&this._canRender()&&this._synchronizedOutputState!==`held`){if(this.input?.syncInputPosition(),this._searchReveal){this._searchReveal=!1;let e=this._search.matches[this.getSearchState().activeIndex],t=e&&Array.from(this.renderer.searchRows()).find(({row:t})=>t===e.start.row);if(t){let e=t.element.getBoundingClientRect(),n=this.element.getBoundingClientRect();this._setScrollTop(this.element.scrollTop+e.top-n.top-(this.element.clientHeight-e.height)/2)}}this._paintSearch(),this._search.resume(this.bridge),this._historySelection.resume(this.bridge),this._historySelection.paintRectangle(this.renderer.searchRows(),this._charWidth),this._textCapture.resume(this.bridge),this._outputAnnouncements.rendered(),this._deliverTitle(),this._drainResponses()}}_deliverTitle(){let e=this.bridge?.getTitle()??null;e!==null&&this.onTitle?.(e)}_drainResponses(){if(!this.bridge)return{hasError:!1};let e,t,n=!1;for(;(e=this.bridge.getResponse())!==null;)try{this.onData&&this.onData(e)}catch(e){n||(n=!0,t=e)}return{hasError:n,error:t}}_collectWindowSizeQueries(e){let t=[],n=this._windowSizeQueryState,r=0;for(;r<e.length;){if(n===0){if(r=typeof e==`string`?e.indexOf(`\x1B`,r):e.indexOf(27,r),r<0)break;n=1,r++;continue}let i=typeof e==`string`?e.charCodeAt(r):e[r];r++;let a=+(i===27);switch(n){case 1:n=i===91?2:a;break;case 2:n=i===49?3:a;break;case 3:n=i===52?4:i===54?6:a;break;case 4:case 6:i===116&&t.push(n===4?14:16),n=a}}return this._windowSizeQueryState=n,t}_windowSizeResponse(e){let{width:t,height:n}=this._pixelSize();if(e===14)return`\x1b[4;${n};${t}t`;let r=Math.max(1,Math.round(this._charWidth));return`\x1b[6;${Math.max(1,Math.round(this._rowHeight))};${r}t`}_pixelSize(){let e=getComputedStyle(this.element),t=(parseFloat(e.paddingLeft)||0)+(parseFloat(e.paddingRight)||0),n=(parseFloat(e.paddingTop)||0)+(parseFloat(e.paddingBottom)||0),r=this.element.clientWidth-t,i=this.element.clientHeight-n;if(r<=0||i<=0){let e=this.element.getBoundingClientRect();r=e.width-t,i=e.height-n}return r<=0&&this._charWidth>0&&(r=this.cols*this._charWidth),i<=0&&this._rowHeight>0&&(i=this.rows*this._rowHeight),{width:Math.max(1,Math.round(r)),height:Math.max(1,Math.round(i))}}_lockHeight(){let e=this._rowHeight||17,t=this.rows*e,n=getComputedStyle(this.element),r=(parseFloat(n.paddingTop)||0)+(parseFloat(n.paddingBottom)||0);n.boxSizing===`border-box`&&(r+=(parseFloat(n.borderTopWidth)||0)+(parseFloat(n.borderBottomWidth)||0)),this.element.style.height=`${t+r}px`}_setRowHeight(){let e=document.createElement(`div`);e.className=`term-row`,e.style.visibility=`hidden`,e.style.position=`absolute`,e.textContent=`W`,this._container.appendChild(e);let t=e.getBoundingClientRect().height;e.remove(),t>0&&(this._rowHeight=t,this.element.style.setProperty(`--term-row-height`,`${t}px`))}_measureCharSize(){let e=document.createElement(`div`);e.className=`term-row`,e.style.visibility=`hidden`,e.style.position=`absolute`;let t=document.createElement(`span`);t.style.width=`auto`,t.textContent=`W`,e.appendChild(t);let n=document.createElement(`span`);n.style.width=`auto`,n.style.letterSpacing=`0`,n.textContent=`▀`,e.appendChild(n),this._container.appendChild(e);let r=t.getBoundingClientRect().width,i=n.getBoundingClientRect().width,a=e.getBoundingClientRect().height;if(e.remove(),r===0||a===0)return null;let o=this._charWidth>0&&(r!==this._charWidth||a!==this._rowHeight);this._charWidth=r,this._rowHeight=a,this.element.style.setProperty(`--term-cell-width`,`${r}px`);let s=i>0?r-i:0;return this.element.style.setProperty(`--term-block-spacing`,Math.abs(s)>.01?`${s}px`:`0px`),o&&this.renderer&&this._scheduleRender(),{charWidth:r,rowHeight:a}}_setupResizeObserver(){let e=document.createElement(`span`);e.className=`term-size-probe`,e.setAttribute(`aria-hidden`,`true`),e.textContent=`W`,this.element.appendChild(e);let t;this.resizeObserver=new ResizeObserver(e=>{if(!this._destroyed){for(let n of e)n.target===this.element&&(t=n.contentRect);this._lastContainerRect=t??null,this._fitAutoResize()}}),this.resizeObserver.observe(e),this.autoResize&&this.resizeObserver.observe(this.element);let n=this.element.ownerDocument.defaultView?.visualViewport;this.autoResize&&n&&(this._visualViewport=n,n.addEventListener(`resize`,this._onVisualViewportChange),n.addEventListener(`scroll`,this._onVisualViewportChange))}_visibleContentHeight(e){let t=this._visualViewport;if(!t||Math.abs(t.scale-1)>.01)return e;let n=this.element.ownerDocument.defaultView?.innerHeight??0,r=t.offsetTop+t.height;if(r>=n)return e;let i=this.element.getBoundingClientRect(),a=getComputedStyle(this.element),o=i.top+(parseFloat(a.borderTopWidth)||0)+(parseFloat(a.paddingTop)||0);return e-Math.max(0,Math.min(o+e,n)-Math.max(o,r))}_setKeyboardInset(e){this._keyboardInset=Math.max(0,e),e<=0?(this._keyboardSpacer?.remove(),this._keyboardSpacer=null):(this._keyboardSpacer||(this._keyboardSpacer=document.createElement(`div`),this._keyboardSpacer.className=`term-keyboard-spacer`,this._keyboardSpacer.setAttribute(`aria-hidden`,`true`),this.element.appendChild(this._keyboardSpacer)),this._keyboardSpacer.style.height=`${e}px`)}_fitAutoResize(){let e=this._lastContainerRect,t=this._measureCharSize();if(!t||!this.autoResize||!e||this._destroyed)return;let{charWidth:n,rowHeight:r}=t,i=e.height,a=this._visibleContentHeight(i),o=Math.max(1,Math.floor(e.width/n)),s=Math.max(1,Math.floor(a/r)),c=this._isScrolledToBottom();this._setKeyboardInset(i-a),o!==this.cols||s!==this.rows?this.resize(o,s):c&&this._scrollToBottom()}destroy(){this._destroyed=!0,this.bridge?.setUpdateListener?.(null),this._textCapture.cancel(),this._historySelection.destroy(),this._rectangleDrag.destroy(),this._outputAnnouncements.destroy(),this._search.cancel(),this.onSearchChange=null,this._windowSizeQueryState=0,this._cancelScheduledRender(),this._cancelSynchronizedOutputFallback(),this.resizeObserver&&this.resizeObserver.disconnect(),this._visualViewportFrame&&cancelAnimationFrame(this._visualViewportFrame),this._visualViewport?.removeEventListener(`resize`,this._onVisualViewportChange),this._visualViewport?.removeEventListener(`scroll`,this._onVisualViewportChange),this._visualViewport=null,this.input&&this.input.destroy(),this.renderer?.destroy(),this.renderer=null,this.element.removeEventListener(`click`,this._onClickFocus),this.element.removeEventListener(`click`,this._onMouseSelect),this.element.removeEventListener(`scroll`,this._onScroll),this.element.ownerDocument.removeEventListener(`copy`,this._onCopy),this.element.ownerDocument.removeEventListener(`visibilitychange`,this._onVisibilityChange),this.element.ownerDocument.removeEventListener(`keydown`,this._onModifierChange),this.element.ownerDocument.removeEventListener(`keyup`,this._onModifierChange),this.element.ownerDocument.defaultView?.removeEventListener(`blur`,this._onWindowBlur),this.element.ownerDocument.defaultView?.removeEventListener(`beforeprint`,this._onBeforePrint),this.element.ownerDocument.defaultView?.removeEventListener(`afterprint`,this._onAfterPrint),this.element.classList.remove(`link-modifier-active`,`term-print-canvas`),this.element.innerHTML=``,this.debug&&globalThis.__wterm===this&&delete globalThis.__wterm,this.debug=null}};export{yt as DebugAdapter,tt as InputHandler,Pe as Renderer,Ot as WTerm,l as WasmBridge,d as WebSocketTransport};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{i as t}from"./queries-CN3JwMBX.js";import{C as n,Et as r,F as i,N as a,O as o,P as s,_ as c,b as l,bt as u,g as d,ht as f,n as p,qt as m,s as h,v as g,y as _}from"./studio-queries-rvbJupCy.js";import{t as v}from"./warnings-V_Ys51wJ.js";import{n as y,r as ee}from"./delivery-path-DJMpRmiY.js";import{c as te,d as b,g as x,l as S,o as ne,u as re}from"./index-n6uo_92S.js";import{n as ie,t as ae}from"./react-CabXf2Ds.js";function C(e){if(Array.isArray(e.questions)&&e.questions.length>0)return e.questions;let t=e;return typeof t.question==`string`?[t]:[]}function oe(e,t){return t===`failed`||t===`interrupted`?null:`Workset ${e} has no failed or interrupted run to retry`}var se=[`start`,`later`,`answer`,`take-control`,`return`,`retry`,`cancel`,`feedback`,`regenerate`,`start-apply`,`publish`],ce=`the AFK runner needs the appliance's factory mode for this companion`;function le(e,t,n,r){let{id:i,stage:a,stageLabel:o}=t,s=n?.state??`idle`;switch(e){case`start`:case`later`:return a===`done`?`Workset ${i} is done`:null}if(!r.runner)return ce;switch(e){case`answer`:return s===`waiting`?null:`this question was already answered`;case`take-control`:return n?.conversation?n.control?`a person already has, or asked for, this Outcome's conversation`:a===`done`?`Workset ${i} is done`:null:`this Outcome has no factory conversation to take over`;case`return`:return n?.control&&n.control.mode!==`automatic`?null:`the factory already drives this Outcome`;case`retry`:return oe(i,s);case`cancel`:return s===`queued`||s===`running`?null:`Workset ${i} has no run to cancel`;case`feedback`:return a===`human-review`||a===`apply`||a===`merge-wait`?null:`Workset ${i} takes no feedback at ${o}; start a new outcome instead`;case`regenerate`:case`start-apply`:return a===`human-review`?null:`Workset ${i} is not in the Human Reviews; it is at ${o}`;case`publish`:return a===`publish`?null:`Workset ${i} is not merged and archived; it is at ${o}`}}function w(e,t,n){return new Set(se.filter(r=>le(r,e,t,n)===null))}function ue(e){if(!e.queuedAt)return null;let t=Date.parse(e.queuedAt);return Number.isNaN(t)?null:t}function de(e,t){return e.rank===null||t.rank===null?e.rank===t.rank?0:e.rank===null?1:-1:e.rank-t.rank||(e.id<t.id?-1:+(e.id>t.id))}var T=e(m(),1),fe=(0,T.createContext)(``);function pe(e,t){let n=(0,T.useRef)(e);(0,T.useEffect)(()=>{n.current=e});let r=(0,T.useRef)(null),i=(0,T.useRef)(t);return(0,T.useEffect)(()=>{let e=r.current;if(!e)return;e.open||i.current(e);let t=t=>{t.target===e&&e.close()},a=()=>n.current();return e.addEventListener(`click`,t),e.addEventListener(`close`,a),()=>{e.removeEventListener(`click`,t),e.removeEventListener(`close`,a)}},[]),r}var E=r(),D=[{kind:`subscription`,tab:`Claude subscription`,label:`Subscription token`,hint:(0,E.jsxs)(`ol`,{className:`note agents-steps`,children:[(0,E.jsxs)(`li`,{children:[`In a terminal on your own machine, run `,(0,E.jsx)(`code`,{children:`claude setup-token`}),`.`]}),(0,E.jsx)(`li`,{children:`Sign in with your Claude account in the browser it opens.`}),(0,E.jsxs)(`li`,{children:[`Paste the token it prints below. It starts with `,(0,E.jsx)(`code`,{children:`sk-ant-oat`}),` and is valid for a year.`]})]})},{kind:`api-key`,tab:`API key`,label:`Anthropic API key`,hint:(0,E.jsx)(`p`,{className:`note`,children:`Agents bill this key. It starts with sk-ant-api.`})}],me={subscription:`Claude subscription token`,"api-key":`Anthropic API key`};function he(e){if(!e)return`Checking…`;if(!e.kind)return`No credential set. Worksets cannot start agents until one is.`;let t=e.source===`studio`?`set in Studio${e.setAt?` on ${new Date(e.setAt).toLocaleString()}`:``}`:`supplied at startup`;return`${me[e.kind]}, ${t}.`}function ge(e,t){e.preventDefault();let n=e.currentTarget,r=new FormData(n).get(t);return n.reset(),typeof r==`string`?r:``}function _e({kind:e,label:t,hint:n,onSaved:r}){let i=x({mutationFn:t=>l(e,t),onSuccess:r});return(0,E.jsxs)(`form`,{className:`factory-sheet`,"data-agents-form":e,onSubmit:e=>i.mutate(ge(e,`value`)),children:[n,(0,E.jsxs)(`label`,{className:`agents-field`,children:[(0,E.jsx)(`span`,{children:t}),(0,E.jsx)(`input`,{type:`password`,name:`value`,autoComplete:`off`,spellCheck:!1,required:!0})]}),(0,E.jsx)(`div`,{className:`factory-sheet-actions`,children:(0,E.jsx)(`button`,{type:`submit`,disabled:i.isPending,children:`Save`})}),i.error?(0,E.jsx)(`p`,{className:`factory-problems`,role:`alert`,children:i.error.message}):null]})}function ve({onClose:e}){let t=f(),n=ie(g()),[r,i]=(0,T.useState)(`subscription`),[a,o]=(0,T.useState)(!1),s=D.find(e=>e.kind===r),l=e=>{t.setQueryData(c,e),o(!0)},u=x({mutationFn:_,onSuccess:e=>{t.setQueryData(c,e),o(!1)}}),d=pe(e,e=>e.showModal?.());return(0,E.jsxs)(`dialog`,{ref:d,className:`outcome-dialog agents-dialog`,"aria-labelledby":`agents-title`,children:[(0,E.jsxs)(`header`,{className:`outcome-dialog-head`,children:[(0,E.jsxs)(`div`,{className:`outcome-dialog-heading`,children:[(0,E.jsx)(`h2`,{id:`agents-title`,children:`Workset agents`}),(0,E.jsx)(`p`,{className:`outcome-dialog-state`,"data-agents-status":``,children:n.error?n.error.message:he(n.data)})]}),(0,E.jsx)(`form`,{method:`dialog`,children:(0,E.jsxs)(`button`,{type:`submit`,className:`outcome-dialog-close`,"aria-keyshortcuts":`Escape`,children:[`Close `,(0,E.jsx)(`kbd`,{children:`Esc`})]})})]}),(0,E.jsxs)(`div`,{className:`agents-dialog-body`,children:[(0,E.jsx)(`div`,{role:`tablist`,"aria-label":`How to sign in`,className:`agents-tabs`,children:D.map(e=>(0,E.jsx)(`button`,{type:`button`,role:`tab`,id:`agents-tab-${e.kind}`,"aria-controls":`agents-panel`,"aria-selected":r===e.kind,onClick:()=>{i(e.kind),o(!1)},children:e.tab},e.kind))}),(0,E.jsx)(`div`,{role:`tabpanel`,id:`agents-panel`,"aria-labelledby":`agents-tab-${r}`,children:(0,E.jsx)(_e,{kind:s.kind,label:s.label,hint:s.hint,onSaved:l},s.kind)}),a?(0,E.jsx)(`p`,{className:`note`,role:`status`,children:`Saved. The next agent start uses it.`}):null,n.data?.source===`studio`?(0,E.jsxs)(`div`,{className:`factory-sheet-actions agents-clear`,children:[(0,E.jsx)(`button`,{type:`button`,onClick:()=>u.mutate(),disabled:u.isPending,children:`Remove the credential set in Studio`}),u.error?(0,E.jsx)(`p`,{className:`factory-problems`,role:`alert`,children:u.error.message}):null]}):null]})]})}function O({action:e,id:t,className:n,children:r,...i}){let a=(0,T.useContext)(fe),o=f(),s=x({mutationFn:n=>d({data:{companion:a,action:e,id:t,fields:n}}),onSuccess:()=>p(o,a)});return(0,E.jsxs)(`form`,{className:n,"data-factory-action":t?`/${t}/${e}`:`/${e}`,onSubmit:e=>{e.preventDefault();let t=e.currentTarget,n=e.nativeEvent.submitter,r={};for(let[e,i]of new FormData(t,n))typeof i==`string`&&(r[e]=i);s.mutate(r,{onSuccess:()=>t.reset()})},"aria-busy":s.isPending||void 0,...i,children:[(0,E.jsx)(`fieldset`,{className:`factory-form-fields`,disabled:s.isPending,children:r}),s.error?(0,E.jsx)(`p`,{className:`factory-problems`,role:`alert`,children:s.error.message}):null]})}function k(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var A=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return A(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return A(t)(e)}}}},j=ae()(((e,t)=>(n,r,i)=>{let a={storage:k(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(...e)=>(f(...e),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return A(u.getItem.bind(u))(a.name).then(e=>{if(e){if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state]}return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{++s,u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p})(e=>({filter:``,setFilter:t=>e({filter:t}),stepped:!1,setStepped:t=>e({stepped:t}),agentsOpen:!1,setAgentsOpen:t=>e({agentsOpen:t})}),{name:`mate.factory.filter`,storage:k(()=>sessionStorage),partialize:({filter:e})=>({filter:e})})),M=`mate.factory.needsYou`;function ye(e,t){let n=e.toLowerCase();return t.toLowerCase().split(/\s+/).every(e=>n.includes(e))}function N(e,t){let n=e.replace(/^\(\d+\) /,``);return t>0?`(${t}) ${n}`:n}function be(e,t,n){let r=t?e.indexOf(t):-1;return r===-1?e[0]:e[Math.min(e.length-1,Math.max(0,r+n))]}function xe(e){return!!e?.closest?.(`input, textarea, select, [contenteditable], .outcome-terminal`)}function Se(e,t){if(/^[1-9]$/.test(t))return e.querySelector(`[data-option-key="${t}"]`);let n={j:`J`,k:`K`}[t];return n?e.querySelector(`[data-outcome-goto][aria-keyshortcuts="${n}"]`):null}function Ce(e,t){return t===`n`?e.querySelector(`form[data-outcome-input] textarea`):t===`/`?e.querySelector(`[data-outcome-filter]`):null}function we(e){return t=>{if(t.defaultPrevented||t.altKey)return;let n=t.target;if(t.key===`Enter`&&(t.ctrlKey||t.metaKey)){let e=n?.closest?.(`form`);if(n?.localName===`textarea`&&e){if(t.preventDefault(),e.querySelector(`button[type="submit"].factory-primary:disabled`))return;let n=e.querySelector(`button[value="start"]`);e.requestSubmit(n??void 0)}return}if(t.ctrlKey||t.metaKey||xe(n))return;let r=e.querySelector(`dialog.outcome-dialog[open]`);if(r){let e=Se(r,t.key);e&&(t.preventDefault(),e.click());return}let i=Ce(e,t.key);if(i){t.preventDefault(),i.focus();return}let a=!!n?.matches?.(`[data-outcome-row]`),o=t.key===`j`||a&&t.key===`ArrowDown`,s=t.key===`k`||a&&t.key===`ArrowUp`;if(!o&&!s)return;let c=be([...e.querySelectorAll(`[data-outcome-row]`)].filter(e=>e.getClientRects().length>0),e.activeElement,o?1:-1);c&&(t.preventDefault(),c.focus(),c.scrollIntoView({block:`nearest`}))}}function Te(){(0,T.useEffect)(()=>{let e=we(document);return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[])}function Ee(e){(0,T.useEffect)(()=>{if(document.title=N(document.title,e),typeof Notification>`u`||Notification.permission!==`granted`)return;let t=0;try{t=Number(sessionStorage.getItem(M)||`0`),sessionStorage.setItem(M,String(e))}catch{}e>t&&new Notification(`Mate factory`,{body:e===1?`1 decision needs you`:`${e} decisions need you`})},[e]),(0,T.useEffect)(()=>()=>void(document.title=N(document.title,0)),[])}function De(){let[e,t]=(0,T.useState)(()=>typeof Notification<`u`&&Notification.permission==="default");return{offered:e,ask:()=>void Notification.requestPermission().then(()=>t(!1))}}function P(e,t){if(t===void 0)return``;let n=Math.max(0,Math.floor((t-Date.parse(e))/6e4));return n>=1440?`${Math.floor(n/1440)}d`:n>=60?`${Math.floor(n/60)}h`:`${n}m`}var F={pieces:[],open:{}},Oe=/^(> |committed: |pushed |published |linked |Returned to automation|no review report |the review report for |\S+ is now at )/;function ke(e){let t=[];for(let n of e.split(/(?<=\n)/)){let e=Oe.test(n)?`factory`:`agent`,r=t.at(-1);r&&(r.kind===e||n.trim()===``)?r.text+=n:t.push({kind:e,text:n})}return t}function I(e,t){let n=(t,n,r)=>{let i=[...e.pieces,r===void 0?{kind:t,text:n}:{id:r,kind:t,text:n}];return{pieces:i,open:r===void 0?e.open:{...e.open,[r]:i.length-1}}},r=(t,r)=>{let i=e.open[t];if(i===void 0)return n(`agent`,r,t);let a=[...e.pieces];return a[i]={...a[i],text:a[i].text+r},{...e,pieces:a}};switch(t.type){case`replay`:{let e={pieces:ke(t.log),open:{}};for(let n of t.open)e=I(e,{type:`text`,...n,delta:n.text});return e}case`text`:return t.id===void 0?n(`agent`,t.delta):r(t.id,t.delta);case`text-end`:{let e=r(t.id,`
|
|
2
|
+
`),{[t.id]:n,...i}=e.open;return{...e,open:i}}case`tool`:return n(`tool`,`› ${t.name} ${t.summary}\n`);case`tool-done`:return t.failed?n(`failed`,` ${t.name} failed\n`):e;case`log`:return n(`factory`,t.text);case`lost`:return n(`factory`,`
|
|
3
|
+
This view fell behind the run; close and reopen the Outcome.
|
|
4
|
+
`);case`settled`:return e}}function Ae(e){let[t,n]=(0,T.useReducer)((e,t)=>t.type===`reset`?{...F,ended:!1}:{...I(e,t),ended:e.ended||t.type===`lost`},{...F,ended:!1});return(0,T.useEffect)(()=>{if(typeof EventSource>`u`)return;n({type:`reset`});let t=new EventSource(e);return t.addEventListener(`message`,e=>{try{n(JSON.parse(e.data))}catch{}}),()=>t.close()},[e]),{pieces:t.pieces,ended:t.ended}}var je=class{mount;outcome;companion;failed;focus;term=null;ws=null;sessionId=null;observer=null;closed=!1;constructor(e,t,n,r,i){this.mount=e,this.outcome=t,this.companion=n,this.failed=r,this.focus=i,this.open()}async open(){try{let e=await te();if(this.closed)return;let t=new e(this.mount,{cursorBlink:!0,autoResize:!1,wasmUrl:a});if(this.term=t,t.onData=e=>this.send({type:`input`,data:e}),t.onResize=()=>this.send({type:`resize`,cols:t.cols,rows:t.rows}),await t.init(),this.closed)return;t.fit(),this.observer=new ResizeObserver(()=>{this.mount.clientWidth&&this.mount.clientHeight&&t.fit()}),this.observer.observe(this.mount),this.connect()}catch{this.term=null,this.failed()}}send(e){b(this.ws,e)}notice(e){this.term?.write(`\r\n\u001b[2m${e}\u001b[0m\r\n`)}start(){if(!this.term)return;let{cols:e,rows:t}=this.term;this.send({type:`start`,workset:this.outcome,companion:this.companion,cols:e,rows:t})}connect(){let e=S();this.ws=e,e.onopen=()=>{if(!this.term)return;let{cols:e,rows:t}=this.term;this.sessionId?this.send({type:`attach`,sessionId:this.sessionId,cols:e,rows:t}):this.start()},e.onmessage=e=>this.receive(e.data),e.onclose=()=>{this.ws===e&&(this.ws=null)}}receive(e){let t=this.term;if(!t)return;if(typeof e!=`string`){t.write(new Uint8Array(e));return}let n=re(e);n&&(n.type===`ready`?(this.sessionId=n.sessionId??null,t.write(`\x1Bc`),this.focus&&t.focus()):n.type===`gone`?(this.sessionId=null,this.start()):n.type===`exit`||n.type===`ended`?(this.sessionId=null,this.notice(`The session ended. Return to automation when you are done, or close and reopen the Outcome to start it again.`)):n.type===`takenOver`?this.notice(`Another tab has this session now.`):n.type===`error`&&n.reason&&this.notice(n.reason))}close(){this.closed=!0,this.observer?.disconnect(),this.ws?.close(),this.ws=null,this.term?.destroy(),this.term=null}};function Me({outcome:e,companion:t,focus:n=!0}){let r=(0,T.useRef)(null),[i,a]=(0,T.useState)(!1),o=(0,T.useRef)(n);return(0,T.useEffect)(()=>{let n=new je(r.current,e,t,()=>a(!0),o.current);return()=>n.close()},[e,t]),(0,E.jsx)(`div`,{ref:r,className:`outcome-terminal`,"data-outcome-terminal":e,"data-companion":t,"data-terminal-error":i?``:void 0,children:i?`The terminal could not start in this browser. Close and reopen the Outcome to retry.`:null})}var Ne=new Set([`queued`,`running`]);function L(e,t){return e.stage===`done`?null:t?.control?.mode===`manual`?`control`:t?.state===`waiting`?`decision`:t?.state===`failed`||t?.state===`interrupted`?`problem`:t&&Ne.has(t.state)?null:e.stage===`human-review`?`review`:e.stage===`merge-wait`?`merge`:e.stage===`publish`?`publish`:null}function R(e,t){return e.workset.id<t.workset.id?-1:+(e.workset.id>t.workset.id)}function z(e){let t=Date.parse(e.run?.updatedAt||e.workset.queuedAt||``);return Number.isNaN(t)?1/0:t}function Pe(e,t){return e.map(e=>({workset:e,run:t?.[e.id]}))}function Fe(e,t){return de({id:e.workset.id,rank:ue(e.workset)},{id:t.workset.id,rank:ue(t.workset)})}function B(e){let t=[e.run?.situations?.[0]?.at,e.run?.updatedAt,e.workset.queuedAt];return Math.max(0,...t.map(e=>Date.parse(e??``)).filter(Number.isFinite))}function V(e){return e.workset.queuedAt!==void 0||e.workset.changes.length>0||e.run!==void 0&&e.run.state!==`idle`}function Ie(e,t){let n=Pe(e,t),r=n.flatMap(e=>{let t=L(e.workset,e.run);return t?[{...e,kind:t}]:[]}).toSorted((e,t)=>z(e)-z(t)||R(e,t)),i=n.filter(e=>e.workset.stage!==`done`);return{attention:r,active:i.filter(V).toSorted(Fe),later:i.filter(e=>!V(e)).toSorted(R),completed:n.filter(e=>e.workset.stage===`done`).toSorted((e,t)=>B(t)-B(e)||R(e,t))}}var H=[{label:`Understood`,after:`clarify-intent`,next:`The factory is working out what you want`},{label:`Approach chosen`,after:`explore`,next:`The factory is choosing the approach`},{label:`Plan ready`,after:`propose`,next:`The factory is writing the plan`},{label:`Plan approved`,after:`human-review`,next:`Ready for your review`},{label:`Built`,after:`apply`,next:`The factory is building it`},{label:`Merged`,after:`merge-wait`,next:`Ready for you to merge`},{label:`Delivered`,after:`publish`,next:`Ready to publish`}];function U(e){return n.indexOf(e)}function Le(e){let t=U(e.stage);return H.map(e=>({label:e.label,reached:t>U(e.after)}))}function W(e,t){return!e.queuedAt&&e.changes.length===0&&(!t||t.state===`idle`)}function Re(e,t){if(e.stage===`done`)return`Delivered`;if(t?.control?.mode===`manual`)return`You have control`;if(t?.state===`waiting`)return`Waiting for your answer`;if(t?.state===`failed`||t?.state===`interrupted`)return`Stopped; needs you`;if(W(e,t))return`Saved for later`;let n=U(e.stage);return H.find(e=>n<=U(e.after))?.next??`Delivered`}var ze={"clarify-intent":`Understanding what you want.`,explore:`Working out the approach.`,propose:`Writing the plan.`,"human-review":`A plan is ready for your review.`,apply:`Building it.`,"merge-wait":`Built; waiting for the merge.`,publish:`Merged; ready to publish.`,done:`Delivered.`};function Be(e,t){return t?.state===`queued`?t.waiting===`workset-slot`?`Waiting for a Workset slot.`:t.waiting===`build-slot`?`Waiting for a build slot.`:`Waiting for a free slot.`:t?.state===`failed`?`Stopped: ${t.reason}`:t?.state===`interrupted`?`Stopped when Studio restarted.`:t?.state===`waiting`?`Waiting for your answer.`:W(e,t)?`Saved for later.`:ze[e.stage]??e.stageLabel}var Ve=new Set([`queued`,`waiting`,`failed`,`interrupted`]);function G(e,t){let n=t?.situations?.[0];return n&&!(t&&Ve.has(t.state))?n:{text:Be(e,t)}}var K={running:`Running`,queued:`Queued`,"needs-you":`Needs you`,control:`You have control`,stopped:`Stopped`,idle:`Idle`,later:`Saved for later`,done:`Delivered`};function q(e,t){return e.stage===`done`?`done`:t?.control?.mode===`manual`?`control`:t?.state===`failed`||t?.state===`interrupted`?`stopped`:t?.state===`running`?`running`:t?.state===`queued`?`queued`:L(e,t)?`needs-you`:V({workset:e,run:t})?`idle`:`later`}var He={"clarify-intent":`clarify-intent`,explore:`explore`,propose:`propose`,"human-review":`reviews`,apply:`apply`,"merge-wait":`archive`,publish:`publish`,done:`complete`},Ue=e=>He[e.stage],We={control:`You have control`,decision:`Decision needed`,review:`Plan ready for review`,merge:`Ready to merge`,publish:`Ready to publish`,problem:`Something went wrong`},Ge={decision:`The run is paused on this. Pick an option or answer in your words; it continues on its own.`,review:`Read each report, then approve to start building, or request a change to revise the plan.`,merge:`Merge the delivery branch on your forge; the board picks it up on its next refresh.`,publish:`Publishing commits, tags and pushes the archived specs to the companion.`,problem:`Retry runs the stage again; take control to fix it yourself.`,control:`You work in the factory's own conversation. Exit Claude, then return the Outcome to automation; the factory checks what changed and continues.`},Ke=`Pauses automation after the current stage; you continue the factory's own conversation here.`,qe=5;function J(e,t){let n=t?.state===`waiting`?C(t).length:0;return e===`decision`&&n>1?`Decisions needed (${n})`:We[e]}var Je=new Set([`answer`,`start-apply`,`publish`,`return`,`retry`,`start`]);function Ye({id:e,action:t,label:n,children:r}){return(0,E.jsxs)(O,{id:e,action:t,className:`factory-action`,children:[r,(0,E.jsx)(`button`,{type:`submit`,className:Je.has(t)?`factory-primary`:void 0,children:n})]})}function Y(e,t){let n=w(e.workset,e.run,t);return(r,i,a)=>t.writable&&n.has(r)?(0,E.jsx)(Ye,{id:e.workset.id,action:r,label:i,children:a}):null}function Xe({activity:e}){return(0,E.jsx)(`span`,{className:`activity-dot`,"data-activity":e,title:K[e],"aria-hidden":`true`})}function Ze({repositories:e,context:t}){return t.writable?e.length===0?(0,E.jsx)(`p`,{className:`note`,children:`Link a Working Repository to this companion to describe outcomes.`}):(0,E.jsxs)(O,{action:`create`,className:`outcome-input`,"data-outcome-input":``,children:[(0,E.jsxs)(`label`,{children:[(0,E.jsx)(`span`,{className:`outcome-input-label`,children:`What should we build or improve?`}),(0,E.jsx)(`textarea`,{name:`text`,rows:3,required:!0,placeholder:`Make onboarding easier: fewer signup steps, and keep authentication working.`})]}),(0,E.jsxs)(`div`,{className:`outcome-input-actions`,children:[(0,E.jsxs)(`button`,{type:`submit`,name:`start`,value:`start`,className:`factory-primary`,children:[`Start `,(0,E.jsx)(`kbd`,{children:`⌘↵`})]}),(0,E.jsx)(`button`,{type:`submit`,name:`start`,value:`later`,children:`Save for later`}),e.length>1?(0,E.jsx)(`select`,{name:`repository`,required:!0,"aria-label":`Working Repository`,children:e.map(e=>(0,E.jsx)(`option`,{value:e,children:e},e))}):null]})]}):(0,E.jsx)(`p`,{className:`note`,children:`Read-only mode. Start Studio with --writable to describe outcomes.`})}function Qe({workset:e}){let t=Le(e),n=t.filter(e=>e.reached).length,r=t.find(e=>!e.reached);return(0,E.jsxs)(`span`,{className:`outcome-row-track`,title:`${n} of ${t.length} milestones${r?`; next: ${r.label}`:``}`,children:[(0,E.jsx)(`span`,{className:`outcome-row-pips`,"aria-hidden":`true`,children:t.map(e=>(0,E.jsx)(`i`,{"data-reached":e.reached?`true`:`false`},e.label))}),(0,E.jsxs)(`span`,{className:`mono`,children:[n,`/`,t.length]})]})}function $e({checks:e}){return e?.length?(0,E.jsx)(`ul`,{className:`outcome-checks`,"aria-label":`Checks`,children:e.map(e=>(0,E.jsxs)(`li`,{"data-passed":e.passed?`true`:`false`,children:[e.passed?`✓`:`✗`,` `,e.name]},e.name))}):null}function et({item:e}){let t=Object.entries(e.run?.reviewReports??{}),n=e.run?.compareUrl;return t.length===0&&!n?null:(0,E.jsxs)(`div`,{className:`outcome-results`,children:[t.map(([e,n])=>(0,E.jsxs)(`a`,{href:`${o}${n}`,target:`_blank`,rel:`noreferrer`,children:[`Review plan`,t.length>1?` · ${e}`:``]},e)),n?(0,E.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,children:`View changes`}):null]})}function tt({item:e}){let t=e.run?.reviewReports??{};return(0,E.jsx)(`div`,{className:`factory-review-reports`,children:e.workset.changes.map(e=>t[e]?(0,E.jsxs)(`figure`,{className:`factory-review-report`,children:[(0,E.jsxs)(`figcaption`,{className:`mono`,children:[e,` ·`,` `,(0,E.jsx)(`a`,{href:`${o}${t[e]}`,target:`_blank`,rel:`noreferrer`,children:`open`})]}),(0,E.jsx)(`iframe`,{src:`${o}${t[e]}`,title:`Review report for ${e}`,loading:`lazy`,sandbox:`allow-scripts allow-modals`})]},e):(0,E.jsxs)(`p`,{className:`note`,"data-report-missing":e,children:[`No review report for `,(0,E.jsx)(`span`,{className:`mono`,children:e}),`.`]},e))})}function nt({item:e,context:t}){if(!t.writable)return null;let{stage:n}=e.workset;return n===`publish`||n===`done`?(0,E.jsxs)(O,{action:`create`,className:`outcome-feedback`,children:[(0,E.jsx)(`textarea`,{name:`text`,rows:2,required:!0,"aria-label":`A new outcome`}),(0,E.jsx)(`button`,{type:`submit`,name:`start`,value:`start`,children:`Start as a new outcome`})]}):Y(e,t)(`feedback`,`Request a change`,(0,E.jsx)(`textarea`,{name:`feedback`,rows:2,required:!0,"aria-label":`Request a change`,placeholder:`What should change?`}))}var rt=e=>e?.state===`running`||e?.state===`queued`;function it({item:e}){let{workset:t,run:n}=e,r=rt(n);return!n?.hasLog&&!r?null:(0,E.jsxs)(`section`,{className:`outcome-log-section`,"aria-label":`Log`,children:[(0,E.jsxs)(`header`,{className:`outcome-section-head`,children:[(0,E.jsx)(`h3`,{children:`Log`}),r?(0,E.jsx)(`span`,{className:`outcome-log-live`,children:`live`}):null,(0,E.jsx)(`a`,{href:s(t.id),target:`_blank`,rel:`noreferrer`,children:`Full log`})]}),(0,E.jsx)(at,{id:t.id})]})}function at({id:e}){let{pieces:t,ended:n}=Ae(i(e)),r=(0,T.useRef)(null),a=(0,T.useRef)(!0),[o,s]=(0,T.useState)(!1);return(0,T.useEffect)(()=>{let e=r.current;e&&t.length>0&&a.current&&(e.scrollTop=e.scrollHeight)},[t]),(0,E.jsxs)(`div`,{className:`outcome-log-frame`,children:[(0,E.jsx)(`pre`,{ref:r,role:`log`,"aria-label":`Run log`,tabIndex:0,onScroll:e=>{let t=e.currentTarget;a.current=t.scrollHeight-t.scrollTop-t.clientHeight<48,s(!a.current)},className:`outcome-log`,"data-outcome-log":i(e),"data-ended":n||void 0,children:t.length>0?t.map((e,t)=>(0,E.jsx)(`span`,{"data-kind":e.kind,children:e.text},t)):(0,E.jsx)(`span`,{className:`outcome-log-empty`,children:`Waiting for output.`})}),o?(0,E.jsx)(`button`,{type:`button`,className:`outcome-log-jump`,onClick:()=>{let e=r.current;e&&(e.scrollTop=e.scrollHeight,a.current=!0,s(!1))},children:`Jump to latest`}):null]})}function ot({item:e,context:t}){let{workset:n,run:r}=e,i=j(e=>e.stepped);return(0,E.jsxs)(`div`,{className:`factory-sheet outcome-control`,children:[(0,E.jsxs)(`div`,{className:`outcome-control-bar`,children:[r?.control?.reason?(0,E.jsx)(`p`,{className:`outcome-control-reason`,children:r.control.reason}):null,Y(e,t)(`return`,`Return to automation`)]}),t.sessions&&r?.control?.mode===`manual`?(0,E.jsx)(Me,{outcome:n.id,companion:t.companionDigest,focus:!i}):(0,E.jsx)(`p`,{className:`note`,children:`The terminal is not available in this Studio.`})]})}function st({item:e,context:t}){let{workset:n,run:r}=e;if(!r?.conversation||r.control||n.stage===`done`)return null;let i=Y(e,t)(`take-control`,`Take control`);return i?(0,E.jsxs)(`div`,{className:`outcome-control-offer`,children:[i,(0,E.jsx)(`p`,{className:`note`,children:Ke})]}):null}function ct({run:e,now:t}){if(e?.control?.mode!==`takeover-requested`)return null;let n=e.state===`running`?e.stage:null,r=e.control.updatedAt?P(e.control.updatedAt,t):``;return(0,E.jsxs)(`section`,{className:`outcome-dialog-attention`,"data-kind":`control`,"data-pending":``,role:`status`,"aria-label":`Taking control`,children:[(0,E.jsx)(`h3`,{children:`Taking control`}),(0,E.jsxs)(`p`,{className:`outcome-attention-hint`,children:[`Control passes to you once`,` `,n?(0,E.jsxs)(E.Fragment,{children:[`the `,(0,E.jsx)(`span`,{className:`mono`,children:n}),` stage`]}):`the current stage`,` `,`ends; the log below keeps following it. The terminal opens here then.`,r?(0,E.jsxs)(`span`,{className:`factory-age mono`,children:[` · asked `,r,` ago`]}):null]})]})}function lt(e,t){if(!e||e.state===`idle`)return`idle`;let n=e.state===`running`?e.startedAt:e.updatedAt;return`${e.state} ${e.stage}${n?` · ${P(n,t)}`:``}`}var ut=({workset:e,run:t})=>e.changes.some(e=>!t?.reviewReports?.[e]);function dt({item:e,context:t}){let{workset:n,run:r}=e,i=Y(e,t),a=rt(r),o=n.stage!==`done`;return(0,E.jsxs)(`div`,{className:`outcome-actions`,role:`group`,"aria-label":`Run actions`,children:[o&&!n.queuedAt?i(`start`,`Start`):null,a?i(`cancel`,`Cancel run`):null,n.stage===`human-review`&&!ut(e)?i(`regenerate`,`Regenerate reports`):null,o&&n.queuedAt?i(`later`,`Move to later`):null]})}function ft({item:e,context:t}){let{workset:n,run:r}=e;return(0,E.jsxs)(`dl`,{className:`outcome-facts`,children:[(0,E.jsx)(`dt`,{children:`Stage`}),(0,E.jsx)(`dd`,{children:n.stageLabel}),(0,E.jsx)(`dt`,{children:`Run`}),(0,E.jsx)(`dd`,{children:lt(r,t.now)}),(0,E.jsx)(`dt`,{children:`Changes`}),(0,E.jsx)(`dd`,{className:`mono`,children:n.changes.join(`, `)||`none yet`}),r?.pushedBranch?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`dt`,{children:`Branch`}),(0,E.jsx)(`dd`,{className:`mono`,children:r.pushedBranch})]}):null,(0,E.jsx)(`dt`,{children:`Id`}),(0,E.jsx)(`dd`,{className:`mono`,children:n.id})]})}function pt(e,t,n){let{run:r}=e,i=K[t].toLowerCase();return r?.state===`running`&&n!==void 0?`${i} · ${P(r.startedAt,n)}`:t===`idle`?``:i}function X(){return(0,E.jsx)(`span`,{className:`factory-recommended`,children:`recommended`})}function mt({item:e,asked:t,round:n,context:r}){let i=r.writable&&w(e.workset,e.run,r).has(`answer`);return(0,E.jsxs)(`div`,{className:`factory-sheet`,children:[(0,E.jsx)(`p`,{className:`factory-question`,children:t.question}),t.options?.length?(0,E.jsx)(`div`,{className:`factory-options`,role:`group`,"aria-label":`Answers`,children:t.options.map((r,a)=>{let o=r===t.recommended,s=a<9?String(a+1):void 0;return i?(0,E.jsxs)(O,{id:e.workset.id,action:`answer`,className:`factory-option`,children:[(0,E.jsx)(`input`,{type:`hidden`,name:`round`,value:n}),(0,E.jsx)(`input`,{type:`hidden`,name:`answer`,value:r}),(0,E.jsxs)(`button`,{type:`submit`,"data-recommended":o?`true`:`false`,"data-option-key":s,"aria-keyshortcuts":s,children:[s?(0,E.jsx)(`kbd`,{"aria-hidden":`true`,children:s}):null,(0,E.jsx)(`span`,{children:r}),o?(0,E.jsx)(X,{}):null]})]},r):(0,E.jsxs)(`span`,{className:`factory-choice`,"data-recommended":o?`true`:`false`,children:[r,o?(0,E.jsx)(X,{}):null]},r)})}):t.recommended?(0,E.jsxs)(`p`,{className:`note`,children:[`Recommended: `,t.recommended]}):null,Y(e,r)(`answer`,t.options?.length?`Send my words`:`Answer`,(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`input`,{type:`hidden`,name:`round`,value:n}),(0,E.jsx)(`textarea`,{name:`answer`,rows:2,required:!0,"aria-label":`Answer in your words`,placeholder:t.options?.length?`Or answer in your words`:`Your answer`})]}))]})}function ht({asked:e,index:t}){return(0,E.jsxs)(`fieldset`,{className:`factory-question-set`,children:[(0,E.jsxs)(`legend`,{className:`factory-question`,children:[(0,E.jsxs)(`span`,{className:`mono`,children:[t+1,`.`]}),` `,e.question]}),e.options?.length?(0,E.jsx)(`div`,{className:`factory-choices`,children:e.options.map(n=>{let r=n===e.recommended;return(0,E.jsxs)(`label`,{className:`factory-choice`,"data-recommended":r?`true`:`false`,children:[(0,E.jsx)(`input`,{type:`radio`,name:`choice-${t}`,value:n}),(0,E.jsx)(`span`,{children:n}),r?(0,E.jsx)(X,{}):null]},n)})}):e.recommended?(0,E.jsxs)(`p`,{className:`note`,children:[`Recommended: `,e.recommended]}):null,(0,E.jsx)(`textarea`,{name:`answer-${t}`,rows:1,"aria-label":`Answer to question ${t+1} in your words`,placeholder:e.options?.length?`Or in your words (overrides the choice)`:`Your answer`})]})}function gt(e,t){let n=new FormData(e),r=0;for(let e=0;e<t;e+=1){let t=n.get(`answer-${e}`);(n.get(`choice-${e}`)||typeof t==`string`&&t.trim())&&(r+=1)}return r}function _t({item:e,questions:t,round:n,context:r}){let[i,a]=(0,T.useState)(0);if(!r.writable||!w(e.workset,e.run,r).has(`answer`))return(0,E.jsx)(`ol`,{className:`outcome-history`,children:t.map(e=>(0,E.jsx)(`li`,{children:e.question},e.question))});let o=e=>{let n=e.currentTarget.closest(`form`);n&&a(gt(n,t.length))},s=t.every(e=>e.recommended);return(0,E.jsxs)(`div`,{className:`factory-sheet`,children:[(0,E.jsxs)(O,{id:e.workset.id,action:`answer`,className:`factory-action factory-round`,children:[(0,E.jsx)(`input`,{type:`hidden`,name:`round`,value:n}),(0,E.jsx)(`div`,{className:`factory-round-questions`,onChange:o,onInput:o,children:t.map((e,t)=>(0,E.jsx)(ht,{asked:e,index:t},e.question))}),(0,E.jsxs)(`div`,{className:`factory-sheet-actions`,children:[(0,E.jsx)(`button`,{type:`submit`,className:`factory-primary`,disabled:i<t.length,children:`Send answers`}),(0,E.jsxs)(`span`,{className:`factory-round-count mono`,"aria-live":`polite`,children:[i,` of `,t.length,` answered`]})]})]}),s?(0,E.jsxs)(O,{id:e.workset.id,action:`answer`,className:`factory-action`,children:[(0,E.jsx)(`input`,{type:`hidden`,name:`round`,value:n}),t.map((e,t)=>(0,E.jsx)(`input`,{type:`hidden`,name:`choice-${t}`,value:e.recommended},e.question)),(0,E.jsx)(`button`,{type:`submit`,children:`Accept all recommendations`})]}):null]})}function vt({item:e,run:t,context:n}){let r=C(t);return r.length===1?(0,E.jsx)(mt,{item:e,asked:r[0],round:t.round??``,context:n}):(0,E.jsx)(_t,{item:e,questions:r,round:t.round??``,context:n})}function yt({item:e,kind:t,context:n}){let{run:r}=e,i=Y(e,n);if(t===`control`)return(0,E.jsx)(ot,{item:e,context:n});if(t===`decision`&&r?.state===`waiting`)return(0,E.jsx)(vt,{item:e,run:r,context:n});if(t===`problem`)return(0,E.jsxs)(`div`,{className:`factory-sheet`,children:[(0,E.jsx)(`p`,{className:`factory-problems`,children:r?.state===`failed`?r.reason:`Stopped when Studio restarted.`}),r?.needsCredential?(0,E.jsx)(At,{label:`Set the agent credential`}):null,i(`retry`,`Retry`)]});if(t===`review`){let t=ut(e);return(0,E.jsxs)(`div`,{className:`factory-sheet`,children:[(0,E.jsx)(tt,{item:e}),(0,E.jsxs)(`div`,{className:`factory-sheet-actions`,children:[i(`start-apply`,`Approve`),t?i(`regenerate`,`Regenerate`):null]}),(0,E.jsx)(nt,{item:e,context:n})]})}return t===`merge`?(0,E.jsx)(`div`,{className:`factory-sheet`,children:r?.compareUrl?(0,E.jsxs)(`a`,{href:r.compareUrl,target:`_blank`,rel:`noreferrer`,children:[`Open `,r.pushedBranch??`the branch`,` to merge`]}):(0,E.jsxs)(`p`,{className:`note`,children:[`Merge `,(0,E.jsx)(`span`,{className:`mono`,children:r?.pushedBranch??`the delivery branch`}),`, then refresh.`]})}):(0,E.jsx)(`div`,{className:`factory-sheet`,children:i(`publish`,`Publish`)})}var bt=e=>`outcome-${e}`;function Z(){let e=u(),t=(t,n=!1)=>void e({to:`/factory`,search:e=>({...e,outcome:t}),replace:n,resetScroll:!1});return{open:e=>t(e),step:e=>t(e,!0),close:()=>t(void 0)}}function Q({item:e,context:t,lead:n,progress:r=!0,trailing:i}){let{workset:a,run:o}=e,s=G(a,o),c=s.at??(o?.updatedAt||a.queuedAt),l=Z();return(0,E.jsxs)(`li`,{className:`outcome-row-item`,"data-workset":a.id,children:[(0,E.jsxs)(`button`,{type:`button`,className:`outcome-row`,"data-outcome-row":``,onClick:()=>{j.getState().setStepped(!1),l.open(a.id)},children:[(0,E.jsx)(Xe,{activity:q(a,o)}),(0,E.jsx)(`span`,{className:`outcome-row-title`,children:a.title}),(0,E.jsx)(`span`,{className:`outcome-row-where`,children:n??s.text}),(0,E.jsx)(`span`,{className:`outcome-row-progress`,children:r?(0,E.jsx)(Qe,{workset:a}):null}),(0,E.jsx)(`span`,{className:`outcome-row-age mono`,children:c?P(c,t.now):``})]}),i]})}function $({label:e,section:t,count:n,children:r}){return(0,E.jsxs)(`section`,{className:`outcome-list-section`,"data-section":t,"aria-label":e,children:[(0,E.jsxs)(`h3`,{children:[e,` `,(0,E.jsx)(`span`,{className:`outcome-list-count mono`,children:n})]}),(0,E.jsx)(`ul`,{className:`outcome-list`,children:r})]})}var xt=(e,t)=>e.replace(/\.$/,``).toLowerCase()===t.replace(/\.$/,``).toLowerCase();function St({to:e,label:t,keyName:n}){let r=Z();return(0,E.jsxs)(`button`,{type:`button`,className:`outcome-step`,"data-outcome-goto":e?bt(e):void 0,disabled:!e,"aria-keyshortcuts":n,onClick:()=>{e&&(j.getState().setStepped(!0),r.step(e))},children:[t,` `,(0,E.jsx)(`kbd`,{children:n})]})}function Ct({item:e,kind:t,context:n}){return(0,E.jsxs)(`section`,{className:`outcome-dialog-attention`,"data-kind":t,"aria-label":`Needs you`,children:[(0,E.jsx)(`h3`,{children:J(t,e.run)}),Ge[t]?(0,E.jsx)(`p`,{className:`outcome-attention-hint`,children:Ge[t]}):null,(0,E.jsx)(yt,{item:e,kind:t,context:n})]})}function wt({item:e,situation:t}){let{workset:n,run:r}=e,i=Re(n,r);return(0,E.jsxs)(`section`,{className:`outcome-dialog-status`,"aria-label":`Where it is`,children:[(0,E.jsx)(`p`,{className:`outcome-situation`,children:t.text}),xt(i,t.text)?null:(0,E.jsxs)(`p`,{className:`outcome-next`,children:[(0,E.jsx)(`span`,{className:`muted`,children:`Next`}),` `,i]}),(0,E.jsx)($e,{checks:t.checks}),(0,E.jsx)(et,{item:e}),n.problems.length>0?(0,E.jsx)(`ul`,{className:`factory-problems`,children:n.problems.map(e=>(0,E.jsx)(`li`,{children:e},e))}):null]})}function Tt({run:e,now:t}){return e?.situations?.length?(0,E.jsxs)(`section`,{className:`outcome-history-section`,"aria-label":`What happened`,children:[(0,E.jsx)(`h3`,{children:`What happened`}),(0,E.jsx)(`ol`,{className:`outcome-history`,children:e.situations.map(e=>(0,E.jsxs)(`li`,{children:[(0,E.jsx)(`span`,{className:`factory-age mono`,children:P(e.at,t)}),(0,E.jsx)(`span`,{children:e.text})]},e.at))})]}):null}function Et({item:e,kind:t,context:n,place:r}){let{workset:i,run:a}=e,o=G(i,a),s=q(i,a),c=a?.state===`running`?a.startedAt:a?.updatedAt||o.at,l=bt(i.id),u={current:Ue(i),activity:s,note:pt(e,s,n.now)},d=pe(Z().close,e=>{e.showModal(),e.querySelector(`.outcome-dialog-close`)?.focus()});return(0,E.jsxs)(`dialog`,{ref:d,id:l,className:`outcome-dialog`,"data-workset":i.id,"data-layout":t===`control`?`control`:void 0,"aria-labelledby":`${l}-title`,children:[(0,E.jsxs)(`header`,{className:`outcome-dialog-head`,children:[(0,E.jsxs)(`div`,{className:`outcome-dialog-heading`,children:[(0,E.jsx)(`h2`,{id:`${l}-title`,children:i.title}),(0,E.jsxs)(`p`,{className:`outcome-dialog-state`,children:[(0,E.jsx)(Xe,{activity:s}),K[s],c?(0,E.jsxs)(`span`,{className:`factory-age mono`,children:[`· `,P(c,n.now)]}):null]})]}),(0,E.jsxs)(`nav`,{className:`outcome-dialog-steps`,"aria-label":`Other outcomes`,children:[(0,E.jsxs)(`span`,{className:`outcome-dialog-place mono`,children:[r.index+1,` of `,r.total]}),(0,E.jsx)(St,{to:r.prev,label:`Previous`,keyName:`K`}),(0,E.jsx)(St,{to:r.next,label:`Next`,keyName:`J`})]}),(0,E.jsx)(`form`,{method:`dialog`,children:(0,E.jsxs)(`button`,{type:`submit`,className:`outcome-dialog-close`,"aria-keyshortcuts":`Escape`,children:[`Close `,(0,E.jsx)(`kbd`,{children:`Esc`})]})})]}),(0,E.jsxs)(`div`,{className:`outcome-dialog-body`,children:[(0,E.jsxs)(`div`,{className:`outcome-dialog-main`,children:[t?(0,E.jsx)(Ct,{item:e,kind:t,context:n}):null,(0,E.jsx)(ct,{run:a,now:n.now}),(0,E.jsx)(it,{item:e}),(0,E.jsx)(wt,{item:e,situation:o}),(0,E.jsx)(dt,{item:e,context:n}),(0,E.jsx)(st,{item:e,context:n}),(0,E.jsx)(Tt,{run:a,now:n.now}),i.intent?(0,E.jsxs)(`section`,{className:`outcome-intent-section`,"aria-label":`Request`,children:[(0,E.jsx)(`h3`,{children:`Request`}),(0,E.jsx)(`p`,{className:`outcome-intent`,children:i.intent})]}):null,t===`review`?null:(0,E.jsx)(nt,{item:e,context:n})]}),(0,E.jsxs)(`aside`,{className:`outcome-dialog-rail`,"aria-label":`Delivery Path`,children:[t===`control`?null:(0,E.jsx)(y,{path:n.path,progress:u,label:`Where it is on the Delivery Path`}),(0,E.jsx)(ft,{item:e,context:n})]})]})]})}function Dt({items:e,context:t,expanded:n}){if(e.length===0)return null;let r=n?[]:e.slice(qe),i=e=>(0,E.jsx)(Q,{item:e,context:t,progress:!1},e.workset.id);return(0,E.jsxs)($,{label:`Done`,section:`completed`,count:e.length,children:[(n?e:e.slice(0,qe)).map(i),r.length>0?(0,E.jsx)(`li`,{children:(0,E.jsxs)(`details`,{className:`outcome-list-more`,children:[(0,E.jsxs)(`summary`,{children:[`Show all `,e.length]}),(0,E.jsx)(`ul`,{className:`outcome-list`,children:r.map(i)})]})}):null]})}function Ot(){return(0,E.jsxs)(`section`,{className:`factory-first-run`,"aria-label":`How the factory works`,children:[(0,E.jsx)(`h3`,{children:`How an outcome gets delivered`}),(0,E.jsxs)(`ol`,{children:[(0,E.jsx)(`li`,{children:`Describe what you want built or improved, and start it.`}),(0,E.jsx)(`li`,{children:`The factory clarifies and explores; answer its questions as they come up.`}),(0,E.jsx)(`li`,{children:`It writes a plan. Review it, then approve or request a change.`}),(0,E.jsx)(`li`,{children:`It builds the plan on a delivery branch. Merge the branch, then publish.`})]}),(0,E.jsx)(`p`,{className:`note`,children:`Everything that needs you shows under Needs you. Open an outcome to follow its log or take control of its conversation.`})]})}function kt(e){let t=j(e=>e.filter).trim(),n=new Map(e.attention.map(e=>[e.workset.id,e.kind])),r=e.active.filter(e=>!n.has(e.workset.id)),i=e=>{if(!t)return!0;let r=n.get(e.workset.id),i=r?J(r,e.run):``;return ye(`${e.workset.title} ${G(e.workset,e.run).text} ${i}`,t)},a=e.attention.filter(i),o=r.filter(i),s=e.later.filter(i),c=e.completed.filter(i);return{kinds:n,query:t,ordered:[...e.attention,...r,...e.later,...e.completed],attention:a,running:{all:r,shown:o},later:s,completed:c,shownCount:a.length+o.length+s.length+c.length}}function At({label:e}){let t=j(e=>e.setAgentsOpen);return(0,E.jsx)(`button`,{type:`button`,"data-open-agents":``,onClick:()=>t(!0),children:e})}function jt({count:e,worksets:t,writable:n,factoryMode:r}){let i=j(e=>e.filter),a=j(e=>e.setFilter),o=De();return(0,E.jsxs)(`div`,{className:`view-intro`,"data-factory-live":``,"data-needs-you":e,children:[t>0?(0,E.jsx)(`input`,{type:`search`,className:`outcome-filter`,"data-outcome-filter":``,placeholder:`Filter outcomes`,"aria-label":`Filter outcomes`,"aria-keyshortcuts":`/`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(a(``),e.currentTarget.blur())}}):null,(0,E.jsxs)(`p`,{className:`factory-keys`,children:[n?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`kbd`,{children:`N`}),` new`]}):null,t>0?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(`kbd`,{children:`/`}),` filter`]}):null,(0,E.jsx)(`kbd`,{children:`J`}),(0,E.jsx)(`kbd`,{children:`K`}),` move `,(0,E.jsx)(`kbd`,{children:`↵`}),` open `,(0,E.jsx)(`kbd`,{children:`1`}),`–`,(0,E.jsx)(`kbd`,{children:`9`}),` answer`]}),(0,E.jsx)(`button`,{type:`button`,"data-factory-notify":``,hidden:!o.offered,onClick:o.ask,children:`Notify me about decisions`}),r&&n?(0,E.jsx)(At,{label:`Agents`}):null]})}function Mt({payload:e,companionDigest:t,writable:n,sessions:r=null,runs:i=null,now:a,openId:o,factoryMode:s=!1}){let c=Ie(e.worksets,i),l={companionDigest:t,writable:n,sessions:r,runner:i!==null,now:a,path:ee({topology:e.topology}).paths[0]},{kinds:u,ordered:d,attention:f,running:p,later:m,completed:h,shownCount:g,query:_}=kt(c),y=o?d.findIndex(e=>e.workset.id===o):-1,te=p.all.length===0&&c.attention.length===0;Te(),Ee(c.attention.length);let b=y>=0?{item:d[y],index:y}:null,x=j(e=>e.agentsOpen),S=j(e=>e.setAgentsOpen);return(0,E.jsx)(fe.Provider,{value:t,children:(0,E.jsxs)(`section`,{className:`view-section factory-home`,"aria-label":`Factory`,children:[(0,E.jsx)(jt,{count:c.attention.length,worksets:e.worksets.length,writable:n,factoryMode:s}),(0,E.jsx)(Ze,{repositories:e.linkedRepositories,context:l}),f.length>0?(0,E.jsx)($,{label:`Needs you`,section:`attention`,count:f.length,children:f.map(e=>(0,E.jsx)(Q,{item:e,context:l,lead:(0,E.jsx)(`span`,{className:`attention-kind`,"data-kind":e.kind,children:J(e.kind,e.run)})},e.workset.id))}):null,p.shown.length>0?(0,E.jsx)($,{label:`Running`,section:`active`,count:p.shown.length,children:p.shown.map(e=>(0,E.jsx)(Q,{item:e,context:l},e.workset.id))}):null,e.worksets.length===0?(0,E.jsx)(Ot,{}):te?(0,E.jsx)(`p`,{className:`note`,children:`The factory is idle. Describe an outcome to get it started.`}):null,(0,E.jsx)(`p`,{className:`note outcome-filter-empty`,"data-outcome-filter-empty":``,hidden:!_||g>0,children:`No outcomes match the filter.`}),m.length>0?(0,E.jsx)($,{label:`Later`,section:`later`,count:m.length,children:m.map(e=>(0,E.jsx)(Q,{item:e,context:l,progress:!1,trailing:Y(e,l)(`start`,`Start`)},e.workset.id))}):null,(0,E.jsx)(Dt,{items:h,context:l,expanded:!!_}),b?(0,E.jsx)(Et,{item:b.item,kind:u.get(b.item.workset.id)??null,context:l,place:{index:b.index,total:d.length,prev:d[b.index-1]?.workset.id,next:d[b.index+1]?.workset.id}},b.item.workset.id):null,e.worksetProblems.length>0?(0,E.jsx)(v,{warnings:e.worksetProblems.map(e=>`${e.path} ${e.reason}`)}):null,(0,E.jsx)(v,{warnings:e.warnings}),s&&n&&x?(0,E.jsx)(ve,{onClose:()=>S(!1)}):null]})})}function Nt(){let{companion:e,outcome:t}=ne.useSearch(),n=u();return(0,T.useEffect)(()=>{let e=/^#outcome-([a-z0-9][a-z0-9-]*)$/.exec(window.location.hash)?.[1];e&&!t&&n({to:`/factory`,search:t=>({...t,outcome:e}),hash:``,replace:!0})},[n,t]),e?(0,E.jsx)(Pt,{companion:e,outcome:t}):null}function Pt({companion:e,outcome:n}){let{data:r}=t(h(e));return r.payload?(0,E.jsx)(Mt,{payload:r.payload,companionDigest:e,writable:r.writable,factoryMode:r.factoryMode,sessions:r.sessions,runs:r.runs,now:r.renderedAt,openId:n}):(0,E.jsx)(`section`,{className:`panel`,children:(0,E.jsx)(`p`,{className:`empty`,children:r.error??`No state collected for this companion.`})})}export{Nt as component};
|